Daily Temperatures With a Monotonic Stack
In this series: Interview patterns in Python
Daily Temperatures is LeetCode 739, rated Medium. Given a list of daily temperatures, answer[i] is how many days you wait until a strictly warmer day. If none exists, the answer is 0. It looks like a nested scan. The interview is whether you notice each day is resolved at most once.
Input: [73, 74, 75, 71, 69, 72, 76, 73]
Output: [1, 1, 4, 2, 1, 1, 0, 0]
73 waits one day for 74. 75 waits four days for 76. 76 never sees a warmer day.
Nested scan, and why they ask this
Brute force is, for each index i, walk j = i + 1 .. n-1 until temperatures[j] > temperatures[i], then write j - i. Worst case that is a strictly decreasing array and you do n + (n-1) + ... + 1 comparisons. Fine for n = 8. Not fine for n in the tens of thousands, which is where the problem lives.
The wasted work is real: when day 0 looks at days 1..k and never finds a warmer value, day 1 is going to look at a subset of the same days. A structure that keeps unresolved days, in an order that lets you drop them the moment a warmer day arrives, is the whole trick. That structure is a stack of indexes, held in decreasing temperature order toward the top.
Walk the example, not the slogan
Start with an answer array of zeros and an empty stack. Walk left to right. The stack always holds days whose warmer day is still in the future, most recent on top, temperatures decreasing as you go toward the top.
i = 0, 73. Stack empty. Push 0. Stack: [0].
i = 1, 74. 74 is strictly greater than 73. Day 0 has found its warmer day. Pop 0, write answer[0] = 1 - 0 = 1. Push 1. Stack: [1]. Output so far: [1, 0, 0, 0, 0, 0, 0, 0].
i = 2, 75. 75 > 74. Pop 1, write answer[1] = 1. Push 2. Stack: [2].
i = 3, 71. 71 is not greater than 75. Do not pop. Push 3. Stack: [2, 3] — temperatures 75 then 71, decreasing toward the top.
i = 4, 69. 69 is not greater than 71. Push 4. Stack: [2, 3, 4] (75, 71, 69).
i = 5, 72. 72 > 69, so day 4 is resolved: answer[4] = 5 - 4 = 1. Pop. 72 > 71, so day 3 is resolved: answer[3] = 5 - 3 = 2. Pop. 72 is not greater than 75, so day 2 stays. Push 5. Stack: [2, 5] (75, 72). Output: [1, 1, 0, 2, 1, 0, 0, 0].
i = 6, 76. 76 > 72, pop 5, answer[5] = 1. 76 > 75, pop 2, answer[2] = 6 - 2 = 4. Push 6. Stack: [6]. Output: [1, 1, 4, 2, 1, 1, 0, 0].
i = 7, 73. 73 is not greater than 76. Push 7. Stack: [6, 7].
The loop ends. Days 6 and 7 are still on the stack. They never found a warmer day. They stay 0, which is what the array was initialized to. You do not need a second pass.
That is the algorithm: while today is strictly warmer than the top, the top has its answer. Then today becomes the new top.
def daily_temperatures(temperatures: list[int]) -> list[int]:
answer = [0] * len(temperatures)
stack: list[int] = [] # indexes, temperatures decrease toward the top
for i, temp in enumerate(temperatures):
while stack and temperatures[stack[-1]] < temp:
prev = stack.pop()
answer[prev] = i - prev
stack.append(i)
return answer
Store indexes, not temperatures. You need the index to write answer[prev] and to compute the distance. If you store temperatures you will not know which day you just resolved.
Why the inequality is strict
The problem asks for a warmer day, not an equal one. The while condition uses <. If today equals the top, today does not resolve it. Push today on top. A later warmer day can still resolve both, and the closer one is on top, so it gets the smaller distance.
Take [70, 70, 71].
- i = 0, 70, push 0.
- i = 1, 70, equal to the top, do not pop, push 1. Stack:
[0, 1]. - i = 2, 71, pops 1 (
answer[1] = 1) then pops 0 (answer[0] = 2).
Correct: [2, 1, 0]. If you had written <=, day 0 would have been resolved at day 1 with distance 1, and 70 is not warmer than 70. That is the case they will type in when your first run is wrong.
The stack remaining decreasing is the invariant. Equals go on top of equals. They are both unresolved. The first strictly warmer day pops a run of them.
Empty input is [] in, [] out. A single day is [0]. A strictly increasing array pops on every step after the first, and every answer is 1. A strictly decreasing array never pops; the stack grows to n; the answer is all zeros. Capacity of the stack is n, not a magic constant.
Complexity, said the way they want it
Each index is pushed once and popped at most once. The inner while across the whole array therefore runs O(n) pops total, not O(n) pops per step. Time is O(n). Extra space is O(n) for the stack (and O(n) for the answer, which the problem requires you to return).
If you say "the while makes it O(n^2)" you have not amortized. Point at the push/pop counts. The answer array is required output; this problem does not let you reuse temperatures in place.
Related shapes, and when this is the wrong stack
Next Greater Element to the right is this loop writing temperatures[i] (the value) into answer[prev] instead of the distance i - prev. Same stack, same strict inequality unless the problem says "greater or equal."
Next greater to the left walks the array right to left. Reverse the scan; do not search this stack.
Circular array is the same stack with the array conceptually walked twice, and you still push each index only on the first pass. Pushing on the second pass duplicates indexes.
Stock span asks how far back you can go while prices are less than or equal to today. You pop smaller-or-equal days to the left and the span is today's index minus the new top. The inequality flips relative to Daily Temperatures, and the direction flips. If you paste this file's while into stock span you will get a wrong answer that looks plausible on increasing input.
Valid Parentheses is the other stack problem interviewers open with: there the stack stores unmatched brackets, here it stores unmatched days. More of these sit in the Technical Interview category.
Do not use a monotonic stack when a single pass with a running max is enough.
What they are listening for
Say the invariant before you code: "stack of indexes, temperatures strictly decreasing toward the top, each index pushed and popped at most once." Write the zeros first, so the leftover days are already correct. Use <, say why not <=, and run [70, 70, 71] out loud. If they ask for complexity, amortize. If they ask for a follow-up, change what you write on pop (distance vs value) before you change the data structure.
The nested scan is the algorithm you mention and discard. The stack is the algorithm you ship.
Keep reading
Subsets: Every Prefix Is a Valid Answer
LeetCode 78 in Python. Emit the power set by recording at every node, recurse with i + 1, and copy the shared buffer before the next pop.
Combination Sum: Reuse the Number, Keep the Index
LeetCode 39 in Python. Enumerate combinations that hit the target, reuse a candidate by staying at the same index, and skip generating permutations.
Generate Parentheses: Backtracking With Two Counts
LeetCode 22 in Python. Build only valid strings with two counters, skip the generate-and-filter trap, and name the Catalan-shaped search tree interviewers expect.
Valid Parentheses: The Stack Problem Every Interview Starts With
LeetCode 20, Valid Parentheses, in Python. Why a stack is the only structure that works, the closing-bracket lookup trick, the three edge cases interviewers check, and the follow-ups that turn an Easy into a design question.
Course Schedule: Topological Sort Detects the Cycle
Given prerequisite pairs, decide if a course plan is possible. Kahn's algorithm in Python, the indegree trick, and the cycle case interviewers actually probe.
LRU Cache: OrderedDict Gives You O(1) Get and Put
Design a least-recently-used cache in Python. Why a hash map alone is not enough, how OrderedDict encodes the recency list, and the capacity edge case.
Newsletter
New posts, straight to your inbox
One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.
Comments
- No comments yet. Be the first.