When a value is popped because a bigger one arrived, the bigger one is its next greater element. So one left-to-right pass answers "how far to the next warmer day" or "next greater element" for every position at once, in O(n) instead of the O(n²) of checking every later item.
When to use it
- For each element you need the nearest greater or smaller element to its left or right.
- The question asks how many days, steps or positions until something bigger or smaller appears.
- You need the span over which each element is the minimum or maximum (largest rectangle in a histogram, sum of subarray minimums).
- A brute force scans forward from every index until it finds a bigger value.
The template
def next_greater(nums):
answer = [-1] * len(nums) # -1 when nothing greater follows
stack = [] # indexes still waiting
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
answer[stack.pop()] = x # x is their next greater
stack.append(i) # values on the stack only decrease
return answerThe variants you will meet
Next greater and next smaller
Pop while the top is smaller than the new value to find next greater elements; pop while it is larger for next smaller. Scanning right to left, or reading the stack top before pushing, gives the nearest one on the left instead.
Spans and distances
Store indexes instead of values and the distance falls out: Daily Temperatures is next greater with i - j as the answer. Largest Rectangle in a Histogram uses the nearest smaller bar on each side to find how wide each bar can stretch.
Time and space complexity
O(n) time even with the inner while loop: each index is pushed once and popped at most once, so there are at most 2n stack operations in total. Space is O(n) for the stack in the worst case, a strictly decreasing input.