Steps to Make Array Non-decreasing - Problem

You're given a 0-indexed integer array nums that might contain elements in decreasing order. Your task is to make this array non-decreasing by repeatedly removing problematic elements.

In each step, you must simultaneously remove all elements nums[i] where nums[i - 1] > nums[i] for all valid indices 0 < i < nums.length. Think of this as a "filtering" process where smaller elements that come after larger elements get eliminated in each round.

Goal: Return the number of steps required until the array becomes non-decreasing (i.e., each element is greater than or equal to the previous element).

Example: [5, 3, 4, 4, 7, 3, 6, 11, 8, 5, 11]
Step 1: Remove 3, 3, 8, 5 → [5, 4, 4, 7, 6, 11, 11]
Step 2: Remove 4, 4, 6 → [5, 7, 11, 11]
Step 3: Remove 5 → [7, 11, 11]
Total: 3 steps

Input & Output

example_1.py — Basic Case
$ Input: [5, 3, 4, 4, 7, 3, 6, 11, 8, 5, 11]
Output: 3
💡 Note: Step 1: Remove [3,3,8,5] → [5,4,4,7,6,11,11]. Step 2: Remove [4,4,6] → [5,7,11,11]. Step 3: Remove [5] → [7,11,11]. Total: 3 steps.
example_2.py — Already Sorted
$ Input: [1, 2, 3, 4, 5]
Output: 0
💡 Note: Array is already non-decreasing, so no steps needed.
example_3.py — Reverse Order
$ Input: [4, 3, 2, 1]
Output: 3
💡 Note: Step 1: Remove [3,2,1] → [4]. Step 2: Remove [2,1] → [3]. Step 3: Remove [1] → [2]. Final result: [4] but we need 3 steps to eliminate everything except the maximum element.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • Array elements can be equal (non-decreasing, not strictly increasing)

Visualization

Tap to expand
🏔️ Mountain Waterfall Elimination53473💧 Water flows down, washing away blocking rocks in each round
Understanding the Visualization
1
Initial State
Array has elements of varying heights like rocks in a waterfall
2
Identify Blocks
Find all positions where flow is blocked (decreasing elements)
3
Simultaneous Removal
All blocking elements are removed at once
4
Repeat Process
Continue until water can flow smoothly (non-decreasing array)
Key Takeaway
🎯 Key Insight: Use a monotonic stack to track 'survivor rounds' - each element knows when it will be eliminated based on conflicts with previous elements!
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 31
43.4K Views
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