IntermediateStack

Monotonic stack: the next greater element

Keep a of indices still waiting for a bigger value. Each new value pops everyone it beats; that's their answer.

The idea

For “next warmer day” or “next greater element”, a looks right from every index: . Instead, walk once and keep a stack of indices that haven't found their answer yet. Their values decrease from bottom to top.

When a new value is bigger than the top, the top's answer is the current index: pop it and repeat. Every index is pushed and popped at most once, so it's .

Worked example

Daily Temperatures: [73, 74, 75, 71, 69, 72, 76]

  1. 73 waits. 74 > 73 → day 0 waited 1. 75 > 74 → day 1 waited 1.
  2. 71, 69 wait under 75. 72 > 69 → day 4 waited 1; 72 > 71 → day 3 waited 2.
  3. 76 beats 72 and 75 → day 5 waited 1, day 2 waited 4.

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

answer ← −1 for every index
stack ← empty(indexes waiting, values falling toward the top)
for each index i, value x:
while stack isn't empty and nums[top] < x:
answer[pop()] ← x
push i
return answer

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

nums = [2, 1, 5, 3]

02
11
25
33

answer

0-1
1-1
2-1
3-1

waiting (values)

empty

Solution · Python

def daily_temperatures(temps):
answer = [0] * len(temps)
stack = [] # indices, temps decreasing
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
j = stack.pop()
answer[j] = i - j
stack.append(i)
return answer

Step 1 of 8

Indexes still waiting for something bigger sit on a stack, their values getting smaller toward the top. Everyone starts with −1 (no answer).

O(n) time, O(n) space.

How to spot it

  • “next greater / smaller”, “days until”, spans, largest rectangle in a histogram.

Common mistakes

  • Pushing values instead of indices, so you can't compute distances.
  • Using <= vs < wrongly for equal values.

Practise the ideas first

Practise it

Go further