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
Steps to Make Array Non-decreasingInitial:53441Step 1:54Step 2:5Result: 2 steps neededRed elements violate non-decreasing property and get removed
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
Asked in
Google 25 Microsoft 20 Amazon 15
29.5K Views
Medium Frequency
~25 min Avg. Time
843 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