You are given an array nums and need to make it non-decreasing (sorted) using a special operation.

Operation Rules:

  • Find all adjacent pairs with the minimum sum in the current array
  • If multiple pairs have the same minimum sum, choose the leftmost one
  • Replace this pair with their sum (merge them into one element)
  • Repeat until the array is non-decreasing

Goal: Return the minimum number of operations needed to make the array non-decreasing.

Example: For [3, 2, 1, 4]:
• Find min sum pairs: (2,1) has sum 3
• Replace → [3, 3, 4] (1 operation)
• Array is now sorted! Answer: 1

Input & Output

example_1.py — Basic Case
$ Input: nums = [3, 2, 1, 4]
Output: 1
💡 Note: The adjacent pair (2, 1) has minimum sum of 3. Replace with their sum to get [3, 3, 4], which is non-decreasing.
example_2.py — Multiple Operations
$ Input: nums = [4, 3, 2, 1]
Output: 3
💡 Note: Step 1: Min sum pair (2,1)=3 → [4,3,3]. Step 2: Min sum pair (3,3)=6 → [4,6]. Step 3: Min sum pair (4,6)=10 → [10]. Total: 3 operations.
example_3.py — Already Sorted
$ Input: nums = [1, 2, 3, 4]
Output: 0
💡 Note: Array is already non-decreasing, so no operations are needed.

Visualization

Tap to expand
Building Block Merger VisualizationConveyor BeltBefore Merge:3214Min sum pair: (2,1) = 3MERGEAfter Merge:334✓ Non-decreasing! Operations: 1Weight: 3Weight: 2Weight: 1Weight: 4Pair Sum: 3
Understanding the Visualization
1
Scan for Pairs
Look at all adjacent building blocks and calculate their combined weight
2
Find Minimum
Identify which pairs have the minimum combined weight
3
Merge Leftmost
Among minimum weight pairs, merge the leftmost one first
4
Check Progress
See if blocks are now in increasing order of weight
Key Takeaway
🎯 Key Insight: The problem requires faithful simulation of the described process - find minimum sum adjacent pairs, pick leftmost on ties, merge, and repeat until sorted.

Time & Space Complexity

Time Complexity
⏱️
O(n³)

O(n) operations in worst case, each taking O(n²) to find minimum and merge

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using constant extra space for tracking indices and values

n
2n
Linear Space

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 104
  • The array will always be sortable using the given operations
Asked in
Google 25 Amazon 18 Meta 15 Microsoft 12
24.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen