Minimum Replacements to Sort the Array - Problem
Transform an Array into Sorted Order Through Strategic Element Splitting

You are given a 0-indexed integer array nums. Your goal is to make the array non-decreasing (sorted) using a special operation.

In one operation, you can replace any element of the array with any two elements that sum to it. This effectively "splits" one element into two smaller parts.

For example:
• Given nums = [5,6,7]
• You can replace nums[1] = 6 with 2 and 4
• Result: [5,2,4,7]

The key insight is that you can only split elements (make them smaller), but you cannot combine them or make them larger. Your task is to find the minimum number of operations needed to create a non-decreasing array.

Challenge: This requires working backwards from the end of the array and using greedy optimization to minimize splits while maintaining the sorted property.

Input & Output

example_1.py — Basic splitting example
$ Input: nums = [3,4,2,6,1]
Output: 3
💡 Note: Working from right to left: 6 > 1, so split into [3,3] (1 op). 4 > 2, so split into [2,2] (1 op). 3 > 2, so split into [1,2] (1 op). Total: 3 operations resulting in [1,2,2,2,3,3,1]
example_2.py — Already sorted
$ Input: nums = [1,2,3,4,5]
Output: 0
💡 Note: Array is already non-decreasing, so no operations are needed
example_3.py — Single large element
$ Input: nums = [20,1]
Output: 19
💡 Note: Need to split 20 into 20 parts of size 1 each: [1,1,1,...,1,1]. This requires 19 operations (20 parts = 19 splits)

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • Each operation splits one element into exactly two elements
  • The sum of split elements must equal the original element

Visualization

Tap to expand
Chocolate Bar Breaking AnalogySize 61Too big! Must break33Perfect! Each ≤ 1Result331Algorithm Steps1. Start from rightmost: max_allowed = 12. Check 6 > 1? YES → Need to split3. Calculate: k = ceil(6/1) = 6 parts needed4. Operations: k-1 = 5 breaks5. Update: max_allowed = 6/6 = 1
Understanding the Visualization
1
Right-to-Left Scan
Start from the end - the last element sets our constraint
2
Check Violation
If current element > max_allowed from right, we need to split
3
Optimal Split
Split into minimum parts: k = ceil(current/max_allowed)
4
Update Constraint
New max_allowed = current/k (maximize for next element)
Key Takeaway
🎯 Key Insight: Work backwards with greedy optimal splitting - each element determines the maximum constraint for elements to its left, and we split to minimize operations while maximizing the next constraint.
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
43.2K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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