Steps to Make Array Non-decreasing - Problem
You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length.
Return the number of steps performed until nums becomes a non-decreasing array.
A non-decreasing array means each element is greater than or equal to the previous element: nums[i] >= nums[i-1].
Input & Output
Example 1 — Basic Case
$
Input:
nums = [5,3,4,4,1]
›
Output:
2
💡 Note:
Step 1: Remove 3,4,1 (violations), left with [5,4]. Step 2: Remove 4, left with [5]. Total: 2 steps
Example 2 — Already Non-decreasing
$
Input:
nums = [4,5,7,7,13]
›
Output:
0
💡 Note:
Array is already non-decreasing, no steps needed
Example 3 — Single Element
$
Input:
nums = [1]
›
Output:
0
💡 Note:
Single element is always non-decreasing
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array with violations: [5,3,4,4,1]
2
Process
Remove violations where nums[i-1] > nums[i]
3
Output
Number of removal steps: 2
Key Takeaway
🎯 Key Insight: Use a monotonic stack to efficiently track how many removal rounds each element survives
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code