Daily Temperatures (LeetCode 739): Solution and Explanation
Given a list of daily temperatures, produce a list where each entry says how many days you must wait after that day to see a strictly warmer temperature. If no warmer day ever comes, the entry is 0.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force is straightforward: for each day, scan forward until you find a warmer one and record the distance. With up to 100,000 days and a mostly decreasing sequence, that is O(n²) comparisons, which is too slow. The waste comes from rescanning the same future days for many different starting days.
Flip the perspective. Instead of each day looking forward for its answer, let each new day resolve the answers of earlier days that are still waiting. When you reach a warm day, every previous day that was colder and has not yet found a warmer day gets its answer right now: the distance between their indices.
Which days are still waiting? Exactly the ones that have not been beaten yet, and they always form a decreasing sequence of temperatures. If an earlier day were colder than a later waiting day, the later day would already have resolved it. So you keep them on a stack, with the coldest unresolved day on top. When a new temperature arrives, you pop while it is warmer than the top, filling in answers as you go, then push the new day.
This is the monotonic stack pattern, and it shows up any time you need the next greater or next smaller element. Every index is pushed once and popped at most once, so the total work is linear even though there is a loop inside a loop.
Approach: Monotonic decreasing stack
- Initialize
resas a list of zeros the same length astemperatures, and an emptystackof (temperature, index) pairs. - Iterate over each day
iwith temperaturet. - While the stack is non-empty and
tis greater than the temperature on top, pop the pair(stackT, stackInd). - For each popped day, set
res[stackInd] = i - stackInd, the number of days it waited. - Push
(t, i)onto the stack, since this day has not found a warmer day yet. - Return
res. Days still on the stack at the end keep their default answer of 0.
Step-by-step example
temperatures = [73,74,75,71,69,72,76,73]
- Day 0 (73): stack is empty, push it. Day 1 (74) beats 73, so pop it and set
res[0]= 1, then push 74. - Day 2 (75) beats 74, so
res[1]= 1, then push 75. - Day 3 (71) and day 4 (69) are colder than the top, so both are pushed. The stack holds 75, 71, 69 from bottom to top.
- Day 5 (72) pops 69 with
res[4]= 1 and 71 withres[3]= 2, stops at 75, and is pushed. - Day 6 (76) pops 72 with
res[5]= 1 and 75 withres[2]= 4, then is pushed. Day 7 (73) is colder and is pushed. - Days 6 and 7 remain on the stack and keep 0. The result is [1,1,4,2,1,1,0,0].
Code: Python, Java, C++
1class Solution:
2 def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
3 res = [0] * len(temperatures)
4 stack = [] # pair: [temp, index]
5
6 for i, t in enumerate(temperatures):
7 while stack and t > stack[-1][0]:
8 stackT, stackInd = stack.pop()
9 res[stackInd] = i - stackInd
10 stack.append((t, i))
11 return res1class Solution {
2 public int[] dailyTemperatures(int[] temperatures) {
3 int[] res = new int[temperatures.length];
4 Stack<Integer> stack = new Stack<>(); // index
5
6 for (int i = 0; i < temperatures.length; i++) {
7 while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
8 int index = stack.pop();
9 res[index] = i - index;
10 }
11 stack.push(i);
12 }
13 return res;
14 }
15}1class Solution {
2public:
3 vector<int> dailyTemperatures(vector<int>& temperatures) {
4 vector<int> res(temperatures.size(), 0);
5 stack<int> stack; // index
6
7 for (int i = 0; i < temperatures.size(); ++i) {
8 while (!stack.empty() && temperatures[i] > temperatures[stack.top()]) {
9 int index = stack.top();
10 stack.pop();
11 res[index] = i - index;
12 }
13 stack.push(i);
14 }
15 return res;
16 }
17};Time and space complexity
O(n)
Each index is pushed exactly once and popped at most once, so the inner while loop does O(n) work in total across the whole run.
O(n)
In a strictly decreasing input, every day stays on the stack, so it can hold n entries. The result array is also size n.
Other approaches
Brute force scan (time O(n²), space O(1) beyond output)
For each day, walk forward until a warmer day appears. It is simple and fine for tiny inputs, but it degrades to quadratic time on long cooling streaks.
Backward pass with jumps (time O(n), space O(1) beyond output)
Iterate from the right. For each day, start at the next day and jump forward using already computed answers (j += res[j]) until a warmer day or a 0 is found. It avoids a stack and still runs in amortized linear time.
Common mistakes
- Popping on
t >= topinstead oft > top. The problem asks for a strictly warmer day, so equal temperatures must stay on the stack. - Storing only temperatures on the stack, which loses the index you need to compute the waiting distance.
- Writing the answer as
i - stackInd - 1. The distance is simply the difference in indices. - Forgetting that unresolved days default to 0, and adding a final loop that overwrites them with something else.
Frequently asked questions
Why does Daily Temperatures use a monotonic stack?
Days still waiting for a warmer day always have decreasing temperatures, so a stack ordered that way holds exactly the unresolved days. Each new warmer day pops and answers them in constant amortized time.
Why is the time complexity O(n) if there is a nested loop?
Each day enters the stack once and leaves at most once. The total number of pops across all iterations is at most n, so the nested loop adds only linear work overall.
Can Daily Temperatures be solved without a stack?
Yes. Process days from right to left and use the answers you have already computed to jump ahead quickly. It is also linear in practice and uses no extra stack.
Is this the same as the next greater element problem?
It is the same pattern. Next greater element asks for the warmer value itself, while this problem asks for the distance to it, so you store indices on the stack.