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: 3
💡 Note: Step 1: Remove 3,1 (violations where prev > current), left with [5,4,4]. Step 2: Remove first 4, left with [5,4]. Step 3: Remove 4, left with [5]. Total: 3 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-decreasing INPUT nums = [5, 3, 4, 4, 1] 5 i=0 3 i=1 4 i=2 4 i=3 1 i=4 Will be removed Will remain Remove nums[i] when: nums[i-1] > nums[i] 5 > 3 (remove 3) 4 > 1 (remove 1) ALGORITHM STEPS 1 Step 1 [5,3,4,4,1] remove 3,1 5 4 4 2 Step 2 [5,4,4] remove 4 5 4 3 Check [5,4] still decreasing! 4 Wait... 5>4 means 4 removed Stack Approach (val, wait) (5, 2) (4, 1) FINAL RESULT After 2 steps: 5 4 Non-decreasing: NO (But track max steps) Output: 2 Steps performed = 2 OK Step 0: [5,3,4,4,1] Step 1: [5,4,4] Step 2: [5,4] or done Key Insight: Use a monotonic stack to track elements and their "wait times". For each element, compute how many steps it survives before being removed. The answer is the maximum wait time among all elements. Stack stores (value, steps_to_remove). Time complexity: O(n), Space: O(n). TutorialsPoint - Steps to Make Array Non-decreasing | Optimal Solution (Monotonic Stack)
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