Python 3D Academyবাংলা

The monotonic stack: the next greater element

🌍 In real life. Students stand in a line at the morning assembly, all facing the stage. Each one asks: who is the first person in front of me who is taller than me? A short student hides behind a tall one, so the tall one answers for everybody shorter behind them at once.

Walk down the line from the back of the room to the front, keeping a pile of the students still waiting for an answer. When a tall student arrives, everyone shorter at the top of the pile has found their answer: it is this student. They leave the pile, and the tall one joins it to wait for someone taller still.

The idea in one sentence: keep a stack of the positions still waiting for a bigger number; when a number arrives, pop every waiting position with a smaller number (this number is their answer), then push the new position.

Its words:

  • next greater element of position i: the first number to the right of i that is bigger than nums[i] (-1 if there is none)
  • monotonic stack: a stack whose numbers only go one way from bottom to top; here they never go up

How it works, step by step:

  1. answer = [-1] * len(nums), and an empty stack of positions
  2. for each position i with number x: while the stack isn't empty and nums[stack[-1]] < x: pop j and set answer[j] = x
  3. push i: it waits for something bigger than x
  4. positions left on the stack at the end keep their -1

Watch each pop answer one question:

Why it is correct. When x at position i pops position j, x is bigger than nums[j]. Is it the first bigger one? Yes: j was still waiting when x arrived, and anything bigger between j and i would already have popped it. And a position still on the stack at the end never met anything bigger, so -1 is right.

Why the stack never goes up. We push x only after popping everything smaller than x, so whatever x sits on is at least as big. That is what lets one bigger number answer a whole run of smaller ones from the top.

What it costs, worked out. Each position is pushed once and popped at most once, so the loop does at most 2n stack operations: O(n) time and O(n) memory. The obvious way, scanning right from every position, can need n(n − 1)/2 checks: for 1,000 numbers that only go down, 499,500 checks against 999.

def next_greater(nums):
    answer = [-1] * len(nums)
    stack = []                      # positions still waiting
    checks = 0
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            checks += 1
            answer[stack.pop()] = x     # x answers the waiting position
        if stack:
            checks += 1                 # the check that stopped the loop
        stack.append(i)
    return answer, checks

def next_greater_slow(nums):
    answer, checks = [-1] * len(nums), 0
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            checks += 1
            if nums[j] > nums[i]:
                answer[i] = nums[j]
                break
    return answer, checks

print(next_greater([2, 7, 3, 5, 4, 6, 1])[0])
falling = list(range(1000, 0, -1))
print(next_greater_slow(falling)[1], next_greater(falling)[1])
The same answers, but on 1,000 falling numbers the slow way checks 499,500 pairs and the stack 999.

Mistakes and edge cases.

  • pushing the number instead of its position: you then can't tell which answer to fill in
  • using <= instead of <: an equal number is not bigger, so [3, 3] must give [-1, -1]
  • forgetting the -1 for positions that never find a bigger number
  • the same trick answers related questions: flip < to > for the next smaller number; for the previous bigger one, walk left to right and read the answer off the top of the stack (the second task)

Quiz

  1. What does this print?

    nums = [4, 5, 2, 10]
    answer = [-1] * len(nums)
    stack = []
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            answer[stack.pop()] = x
        stack.append(i)
    print(answer)
  2. What does the stack hold while the loop runs?

    • The positions still waiting for a bigger number; their numbers never go up from bottom to top
    • Every number seen so far, in sorted order
    • The answers found so far
  3. Why is the monotonic stack O(n), even with a while loop inside the for loop?

    • Each position is pushed once and popped at most once, so all the pops together are at most n
    • The while loop runs at most once per number
    • The numbers are sorted first
  4. For [3, 3] this answers [3, -1], but 3 is not bigger than 3. Which line is wrong?

    def next_greater(nums):
        answer = [-1] * len(nums)
        stack = []
        for i, x in enumerate(nums):
            while stack and nums[stack[-1]] <= x:
                answer[stack.pop()] = x
            stack.append(i)
        return answer

Coding tasks

  1. Write next_greater(nums) in O(n) with a monotonic stack: for each position, the first number to its right that is bigger, or -1.

  2. Write previous_greater(nums) in O(n): for each position, the nearest number to its left that is bigger, or -1.