TRACK B · ALGORITHMmedium•NOVEMBER 2026•6 MIN
Monotonic Stack: Next Greater & Histogram Spans
Resolve 'next warmer / next shorter' queries in O(n) by keeping waiting indices strictly ordered.
monotonic stackstacksarraysamortized
The core idea
Keep a stack of indices still waiting for a bigger (or smaller) neighbor. Whenever a new element resolves the top of the stack, pop and record its distance—every element is pushed once and popped at most once.
Watch it run
Step through the trace below (or turn on Predict Mode) to watch the invariant hold at every step.
LOADING MONOTONIC STACK SIM...
What to say out loud
Canonical Python template
def daily_temperatures(temps: list[int]) -> list[int]:
stack, ans = [], [0] * len(temps)
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
prev = stack.pop()
ans[prev] = i - prev
stack.append(i)
return ans