Browse curriculum

Daily Temperatures

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

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};

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.

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

AI resume checker — match your resume to the job description