Browse curriculum

Daily Temperatures (LeetCode 739)

Daily Temperatures (LeetCode 739): find how many days you have to wait for a warmer temperature.

Problem Understanding

temperatures[i] is the temperature on day i. Build an array answer where answer[i] counts the days from day i until the first strictly warmer day. If no warmer day ever comes, answer[i] stays 0.

Algorithm Strategy

We use a Monotonic Decreasing Stack.

  1. Initialize answer array with 0s.
  2. Use a stack to store indices of days.
  3. Iterate through temperatures.
  4. While the current temperature is warmer than the temperature at the index stored in stack.top():
    • We found a warmer day for stack.top()!
    • Pop the index (prevIndex).
    • Calculate days waiting: i - prevIndex.
    • Update answer[prevIndex].
  5. Push current index i onto the stack.

Interactive Visualization

8 DAYS

ANSWER = 0

temperatures · answer

73
0

0

74
0

1

75
0

2

71
0

3

69
0

4

72
0

5

76
0

6

73
0

7

stack · waiting days

empty

Waiting

0

Answered

0

 

answer starts as zeros: a day with no warmer day after it keeps 0

Next

Day 0: 73°

Free preview: the first 8 of 24 steps

Temps

Visualize how the monotonic stack keeps track of 'unresolved' cooler days.

Dry Run

Input: [73, 74, 75, 71, 69, 72]

Day Temp Stack (Indices) Action
0 73 [0] Push 0
1 74 [] -> [1] 74 > 73. Pop 0. ans[0] = 1-0 = 1. Push 1.
2 75 [] -> [2] 75 > 74. Pop 1. ans[1] = 2-1 = 1. Push 2.
3 71 [2, 3] 71 < 75. Push 3.
4 69 [2, 3, 4] 69 < 71. Push 4.
5 72 [2] -> [2, 5] 72 > 69 (Pop 4). 72 > 71 (Pop 3). Push 5.

Edge Cases & Common Mistakes

  • Decreasing Order: [90, 80, 70]. Stack just grows. Output all 0s.
  • Stack Contents: Remember to store indices, not values.

Solution

Monotonic Stack O(N).

Daily Temperatures Code
1var dailyTemperatures = function(temperatures) {
2 const n = temperatures.length;
3 const answer = new Array(n).fill(0);
4 const stack = []; // indices
5
6 for (let i = 0; i < n; i++) {
7 while (stack.length > 0 && temperatures[i] > temperatures[stack[stack.length - 1]]) {
8 const idx = stack.pop();
9 answer[idx] = i - idx;
10 }
11 stack.push(i);
12 }
13 return answer;
14};

Daily Temperatures in Python, Java, C++, TypeScript and C

Daily Temperatures in Python
class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        n = len(temperatures)
        answer = [0] * n
        stack = [] # stores indices
        
        for i, t in enumerate(temperatures):
            while stack and t > temperatures[stack[-1]]:
                idx = stack.pop()
                answer[idx] = i - idx
            stack.append(i)
            
        return answer
Daily Temperatures in Java
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] answer = new int[n];
        Stack<Integer> stack = new Stack<>();
        
        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                int idx = stack.pop();
                answer[idx] = i - idx;
            }
            stack.push(i);
        }
        return answer;
    }
}
Daily Temperatures in C++
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int n = temperatures.size();
        vector<int> answer(n, 0);
        stack<int> st;
        
        for (int i = 0; i < n; i++) {
            while (!st.empty() && temperatures[i] > temperatures[st.top()]) {
                int idx = st.top(); st.pop();
                answer[idx] = i - idx;
            }
            st.push(i);
        }
        return answer;
    }
};
Daily Temperatures in TypeScript
function dailyTemperatures(temperatures: number[]): number[] {
    const n = temperatures.length;
    const answer: number[] = new Array(n).fill(0);
    const stack: number[] = []; // indices
    
    for (let i = 0; i < n; i++) {
        while (stack.length > 0 && temperatures[i] > temperatures[stack[stack.length - 1]]) {
            const idx = stack.pop()!;
            answer[idx] = i - idx;
        }
        stack.push(i);
    }
    return answer;
};
Daily Temperatures in C
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* dailyTemperatures(int* temperatures, int temperaturesSize, int* returnSize) {
    int* answer = (int*)calloc(temperaturesSize, sizeof(int));
    int* stack = (int*)malloc(temperaturesSize * sizeof(int));
    int top = -1;
    
    for (int i = 0; i < temperaturesSize; i++) {
        while (top >= 0 && temperatures[i] > temperatures[stack[top]]) {
            int idx = stack[top--];
            answer[idx] = i - idx;
        }
        stack[++top] = i;
    }
    
    *returnSize = temperaturesSize;
    free(stack);
    return answer;
}

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Start with zeros

    Set every answer to 0 and the stack empty.

  2. Pop cooler days

    While today is warmer than the day on top, pop it and set its answer to today's index minus its index.

  3. Push today

    Push today's index to wait for a warmer day.

Frequently asked questions

How does a monotonic stack solve Daily Temperatures?

Keep the indices of days still waiting, coolest on top. When a warmer day arrives, pop each cooler day and set its answer to the distance between the two indices.


Why store indices instead of temperatures?

The answer is a number of days, which is the difference between indices, and it has to be written to the day that waited.


What is the time complexity?

O(n): each day is pushed once and popped at most once. The stack and answer array take O(n) space.

New to the technique behind this problem? Watch it run step by step:

Stack Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description