Stack patterns: daily temperatures and stock span
🌍 In real life. It is January in Dhaka and the mornings are cold. For each morning you want to know: how many days until a warmer one? That is the next greater element again, but the answer is a distance in days, not the warmer temperature itself.
A vegetable seller watches the price of onions instead. Each evening she asks: for how many days in a row, counting today, has the price been at or below today's? If the price is the highest for a week, the answer is 7. That number is the span, a classic question about share prices too. It is the same pattern looking back: the previous bigger price ends the span.
The idea in one sentence: whenever a question asks for the next or previous bigger (or smaller) item, or how far it is, keep a monotonic stack of positions and let each pop answer one of them.
Its words:
- monotonic stack: a stack whose values only go one way from bottom to top
- next greater: the first later item that is bigger than this one
- span: how many days in a row, counting back from today, the price was at or below today's
Three questions decide the code:
- what waits on the stack? positions (so you can measure distances)
- which way is it sorted? for "warmer", the temperatures never rise from bottom to top
- what does a pop answer? a warmer day i pops day j, so day j waited
i - jdays
Daily temperatures, step by step:
answer = [0] * len(temps)(0: no warmer day comes)- for each day i: while the coldest waiting day on top is colder than today, pop it as j and set
answer[j] = i - j - push i
A week of January mornings:
Why it is correct. It is the argument of 39.3: a day still on the stack has met nothing warmer, so the first warmer day to pop it is the first warmer day after it, and i - j is how long it waited. Days left on the stack keep 0.
The stock span looks back. For today's price, pop every earlier day whose price is at or below today's: they are inside today's span, and they can never end a later day's span either, because today's price is at least as big and nearer. Whatever is left on top is the previous bigger price, and the span reaches back to just after it: i - stack[-1], or i + 1 if nothing is left.
What it costs. Both walks push each day once and pop it at most once: O(n) time and O(n) memory. Asking each day separately can cost n(n − 1)/2 comparisons: 1,000 days that only get colder, or 1,000 rising prices, take 499,500 comparisons against about 1,000.
def days_to_wait(temps):
answer = [0] * len(temps)
stack = [] # days still waiting
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
j = stack.pop()
answer[j] = i - j # day j waited until day i
stack.append(i)
return answer
def stock_span(prices):
spans = []
stack = [] # days with a bigger price than everything after them so far
for i, p in enumerate(prices):
while stack and prices[stack[-1]] <= p:
stack.pop()
spans.append(i - stack[-1] if stack else i + 1)
stack.append(i)
return spans
print(days_to_wait([14, 13, 15, 12, 11, 16, 15, 17]))
print(stock_span([100, 80, 60, 70, 60, 75, 85]))Mistakes and edge cases.
- writing the temperature (
answer[j] = t) or the day (answer[j] = i) instead of the distancei - j - for the span, popping only smaller prices (
<): an equal price is inside the span too - for the span, forgetting the case where the stack is empty: then the span is every day so far,
i + 1 - spotting the pattern: "next warmer", "previous higher", "how many days until", "how far back" all mean a monotonic stack
Quiz
What does this print?
temps = [20, 18, 22] answer = [0] * len(temps) stack = [] for i, t in enumerate(temps): while stack and temps[stack[-1]] < t: j = stack.pop() answer[j] = i - j stack.append(i) print(answer)Prices: [100, 80, 60, 70, 60, 75, 85]. What is the span on the day the price is 85?
- 6
- 7
- 1
For [20, 18, 22] this answers [2, 2, 0] instead of [2, 1, 0]. Which line is wrong?
def days_to_wait(temps): answer = [0] * len(temps) stack = [] for i, t in enumerate(temps): while stack and temps[stack[-1]] < t: j = stack.pop() answer[j] = i stack.append(i) return answerWhich question is a job for a monotonic stack?
- For each day, how many days until more rain than today
- The average rainfall of the month
- Whether it rained on the 5th
What does the stock span with a stack cost for n days?
- O(n): each day is pushed once and popped at most once
- O(n²): each day looks back at every earlier day
- O(log n)
Coding tasks
Write
days_to_wait(temps)in O(n): for each day, how many days until a warmer one, or 0 if none comes.Write
stock_span(prices)in O(n): for each day, how many days in a row, counting that day, the price has been at or below that day's price.