Magicsheet logo

Steps to Make Array Non-decreasing

Medium
49.7%
Updated 6/1/2025

Steps to Make Array Non-decreasing

What is this problem about?

The Steps to Make Array Non-decreasing coding problem describes a process where in each step, you remove any element arr[i]arr[i] if arr[i1]>arr[i]arr[i-1] > arr[i]. This happens simultaneously for all such elements. You repeat this process until the array becomes non-decreasing. Your goal is to find the total number of steps required to reach this state.

Why is this asked in interviews?

This is a challenging "Medium" problem asked by Meta and Google. It tests your ability to move from a literal simulation (which would be too slow) to a more abstract representation using a Monotonic Stack interview pattern. It requires deep insight into how elements "block" each other and how long it takes for an element to be "consumed" by a larger element to its left.

Algorithmic pattern used

The optimal pattern is a Monotonic Stack. You iterate through the array from right to left (or left to right with slightly different logic). For each element, you want to know how many steps it will take to be removed. An element is removed by the first larger element to its left. The number of steps it takes depends on how many smaller elements were already removed between it and that larger element. You use a stack to keep track of elements and the number of steps they "survived."

Example explanation (use your own example)

Array: [10, 1, 2, 3, 4].

  • Step 1: 10 is > 1. 1 is removed. Array becomes [10, 2, 3, 4].
  • Step 2: 10 is > 2. 2 is removed. Array becomes [10, 3, 4].
  • Step 3: 10 is > 3. 3 is removed. Array becomes [10, 4].
  • Step 4: 10 is > 4. 4 is removed. Array becomes [10]. Total steps: 4. Notice how 10 "eats" its neighbors one by one. If we had [10, 5, 2, 11, 3], the 10 would eat 5 and 2 simultaneously, but then the process would stop because 11 > 10.

Common mistakes candidates make

  • Naive Simulation: Literally removing elements and rebuilding the array, which can be O(N2)O(N^2).
  • Stack logic errors: Failing to correctly track the "survival time" of elements in the stack.
  • Incorrect direction: Iterating in a direction that doesn't allow for easy calculation of the "eating" process.
  • Missing simultaneous removals: Not realizing that multiple elements can be removed in the same step.

Interview preparation tip

Monotonic stacks are often used for problems involving "the next larger/smaller element." When a problem also involves a "time" or "step" component, you often need to store an additional value in your stack representing that time.

Similar Questions