15% off all plans & roadmaps Use code

See plans

Daily Temperatures

Updated

TL;DR: For each day, find how many days until a strictly warmer temperature, or 0 if none exists. A monotonic stack of unresolved day indices answers every day in one left-to-right pass.

Problem

You are given an array of integers temperatures, where each value is the temperature on one day. Return an array answer where answer[i] is the number of days you must wait after day i to reach a warmer temperature. If no later day is warmer, set answer[i] = 0.

Example 1

Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]

Example 2

Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]

Example 3

Input: temperatures = [30,60,90]
Output: [1,1,0]

Constraints

  • 1 <= temperatures.length <= 10^5
  • 30 <= temperatures[i] <= 100

Constraints that matter

  • temperatures.length up to 10^5 rules out O(n^2) in the worst case. A strictly falling array makes the nested scan do about 5 * 10^9 comparisons.
  • The answer needs distances between positions, so you must remember indices, not only temperature values.
  • temperatures[i] only ranges from 30 to 100, which allows a bucket-by-temperature solution with 71 buckets, but the stack works without relying on that range.
  • The wait must be for a strictly warmer day, so equal temperatures do not resolve a pending day.

View on LeetCode

Hints

Hint 1

This is a next greater element problem.

Hint 2

For each day i, scan forward through days i + 1, i + 2, and so on until you find a temperature greater than temperatures[i].

Solution

Intuition

This is a next greater element problem. For each position you want the nearest position to its right that holds a larger value. The pattern is a monotonic stack.

Picture a board of sticky notes, each one a day still waiting for a warmer day, with the coldest note on top. When a warm day arrives, it peels off every note colder than itself and writes the gap in days on each one, so the stack is the board and popping is peeling notes off.

The signal is the phrase "first later day that beats today." Brute force looks forward from every day and rescans the same future days many times. A stack flips the direction: walk left to right and keep the days that are still waiting for a warmer day.

The waiting days form a decreasing sequence of temperatures. If a waiting day were colder than a later waiting day, the later day would already have resolved it. So the stack stays sorted by temperature, with the coldest waiting day on top.

When a new day arrives, every waiting day colder than it is resolved at once. Those are exactly the days at the top of the stack. You pop them, record i - popped_index, then push the new day. Each day enters and leaves the stack at most once, which gives O(n).

Watch the pattern animation

Worked example

Input: temperatures = [100, 99, 98, 97]
Output: [0, 0, 0, 0]
Explanation: The temperatures fall every day, so no day ever sees a strictly warmer day after it. Every answer stays 0. This is the worst case for both approaches, because nothing ever gets resolved early.

Approach 1: Brute force

For each day i, scan forward through days i + 1, i + 2, and so on until you find a temperature greater than temperatures[i]. The distance to that day is the answer. If the scan reaches the end, the answer stays 0.

This is correct because the first warmer day found while scanning left to right is the nearest one.

Steps

  1. Create answer of length n filled with 0.
  2. For each index i from 0 to n - 1, start an inner loop at j = i + 1.
  3. If temperatures[j] > temperatures[i], set answer[i] = j - i and stop the inner loop.
  4. If the inner loop ends without a hit, leave answer[i] at 0.
  5. Return answer.

Dry run

Trace on [100, 99, 98, 97].

  • i = 0 (100): scan 99, 98, 97. None is greater. answer[0] = 0. 3 comparisons.
  • i = 1 (99): scan 98, 97. None is greater. answer[1] = 0. 2 comparisons.
  • i = 2 (98): scan 97. Not greater. answer[2] = 0. 1 comparison.
  • i = 3 (97): nothing to scan. answer[3] = 0.

The result is [0, 0, 0, 0]. Six comparisons for four days, which is n * (n - 1) / 2.

Complexity

TimeO(n^2)
SpaceO(1) extra, not counting the output array

Here n is the number of days. In the worst case, such as a strictly falling array, day i scans all n - 1 - i later days, and the sum is n * (n - 1) / 2. That is about 5 * 10^9 comparisons at n = 10^5, which is too slow. Beyond the output array you keep only a few integer variables.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        n = len(temperatures)
        answer = [0] * n
        for i in range(n):
            for j in range(i + 1, n):
                if temperatures[j] > temperatures[i]:
                    answer[i] = j - i
                    break
        return answer
Monotonic Stack pattern infographic for Daily Temperatures

Solution pattern

Monotonic Stack

Part of Stack Patterns

Approach 2: Monotonic stack of indicesOptimalMonotonic Stack

What's slow: brute force rescans the same future days for many different starting days. If days 3 and 4 are both waiting on day 7, each one walks over days 5 and 6 on its own.

The insight that fixes it: move left to right and keep a stack of indices whose answer is still unknown. When day i arrives, every waiting day with a lower temperature has found its warmer day. Pop them, write i - index for each, then push i.

The stack stays in decreasing temperature order from bottom to top. That means all days that i can resolve sit together at the top, so you stop popping at the first day that is at least as warm as i.

Why it is correct. Every day still on the stack has not yet seen a warmer day, so its first warmer day lies ahead. When day i beats a stacked day, no day between them was warmer, since any such day was either not warmer or was popped earlier. Stopping at the first top that is at least as warm is safe because the stack is sorted, so every deeper day is at least as warm too.

Steps

  1. Create answer of length n filled with 0, and an empty stack of indices.
  2. For each index i from 0 to n - 1, read temperatures[i].
  3. While the stack is not empty and temperatures[i] is greater than the temperature at the top index, pop that index p.
  4. Set answer[p] = i - p for every popped index.
  5. Push i onto the stack.
  6. After the loop, indices left on the stack have no warmer day, so their answers stay 0.
  7. Return answer.

Dry run

Trace on [100, 99, 98, 97]. Each day is colder than the one on top of the stack, so nothing pops.

itemptop temppopsanswer after stepstack after step
0100(empty)none[0, 0, 0, 0][0]
199100none, 99 is not greater[0, 0, 0, 0][0, 1]
29899none[0, 0, 0, 0][0, 1, 2]
39798none[0, 0, 0, 0][0, 1, 2, 3]

The loop ends with all four indices still waiting, so every answer stays 0. The result is [0, 0, 0, 0].

For contrast, take [73, 74, 75, 71, 69, 72, 76, 73]. At i = 5 (72), the stack is [2, 3, 4]. Index 4 (69) pops with answer 1, index 3 (71) pops with answer 2, and index 2 (75) stays because 72 is not greater than 75. At i = 6 (76), indices 5 and 2 pop with answers 1 and 4.

Complexity

TimeO(n)
SpaceO(n)

Here n is the number of days. The outer loop runs n times. Each index is pushed exactly once and popped at most once. So the total number of pops across the whole run is at most n, even though the inner while loop sits inside the outer loop, and that gives about 2n stack operations in total.

The stack holds up to n indices in the worst case, a strictly falling array. The answer array also has n entries, so space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        n = len(temperatures)
        answer = [0] * n
        stack = []  # indices of days still waiting for a warmer day
        for i, temp in enumerate(temperatures):
            while stack and temp > temperatures[stack[-1]]:
                prev = stack.pop()
                answer[prev] = i - prev
            stack.append(i)
        return answer

Common mistakes

  • Pushing temperature values with stack.append(temp) instead of indices. You then cannot compute i - prev. Store the index and read the temperature through temperatures[index].
  • Using >= in while stack and temp >= temperatures[stack[-1]]. An equal temperature is not warmer, so it must not resolve the waiting day. Use a strict >.
  • Pushing i before the while loop. The new day would compare against itself and pop immediately with answer 0. Pop first, then push.
  • Filling answer with a sentinel such as -1 and forgetting to reset leftovers. Days that never find a warmer day must be 0, so initialise the whole array to 0 and leave leftovers alone.
  • Popping only once with if instead of while. One warm day can resolve several waiting days, as 76 does for 72 and 75 in the contrast trace. Loop until the top is no longer colder.
  • Writing answer[i] = i - prev instead of answer[prev] = i - prev. The distance belongs to the day that was waiting, not the day that arrived.

Edge cases

  • A single day, [50]: no later day exists, so the output is [0].
  • Strictly falling temperatures, [100, 99, 98, 97]: nothing ever pops, so the output is all 0 and the stack grows to size n.
  • Strictly rising temperatures, [30, 40, 50, 60]: every day resolves on the next one, giving [1, 1, 1, 0], and the stack never holds more than one index.
  • All equal, [70, 70, 70]: equal is not warmer, so the output is [0, 0, 0].
  • A late spike after a long fall, [90, 80, 70, 60, 100]: the last day pops four indices at once, giving [4, 3, 2, 1, 0].
  • Maximum size, n = 100000: the stack approach does about 2 * 10^5 operations, while brute force can hit billions.

Follow-ups interviewers ask

Can you solve it with O(1) extra space beyond the output?
Yes. Walk from right to left and reuse answer as a chain of jump pointers. For day i, start at j = i + 1. While temperatures[j] <= temperatures[i], jump to j + answer[j], and stop with answer 0 if answer[j] is 0. The jumps follow the same chain the stack would hold, so total work stays O(n) amortized.
The temperatures are only between 30 and 100. Does that give a different solution?
It does. Go right to left and keep nextDay[t], the nearest index seen so far with temperature t. For day i, check temperatures t + 1 through 100 and take the smallest index. That costs at most 70 lookups per day, so O(71 * n), which is linear but with a larger constant than the stack.
What if temperatures arrive as a stream and you must answer later?
Keep the same stack and process each reading as it arrives. When a new reading pops waiting days, you can emit their final answers immediately. Days still on the stack are unresolved until a warmer reading shows up. This is the same idea as Online Stock Span.

Daily Temperatures FAQ

What is the time complexity of Daily Temperatures?

The monotonic stack solution runs in O(n) time and uses O(n) space, where n is the number of days. Each index is pushed once and popped at most once. The brute force scan is O(n^2) in the worst case.

Why use a monotonic stack for Daily Temperatures?

Each day waits for the next strictly warmer day, and the waiting days always have decreasing temperatures. That order puts every day a new reading can resolve at the top of the stack. You pop them in one batch and never revisit them.

Should the stack store indices or temperatures in LeetCode 739?

Store indices. The answer is a distance between positions, and you can look up any temperature from its index. Storing only temperatures loses the position and also breaks on repeated values.

Can Daily Temperatures be solved in O(1) extra space?

Yes, apart from the output array. A right-to-left pass that follows jump pointers stored in answer needs no stack and stays O(n) amortized. The stack version is easier to write and explain, so it is the usual interview answer.

How does Daily Temperatures differ from Next Greater Element?

Next Greater Element asks for the value of the next larger item, while Daily Temperatures asks for the index distance to it. The stack logic is the same, so you store indices and subtract them. Both use a strict comparison for greater.

Why does the while loop not make Daily Temperatures O(n^2)?

The inner loop only pops, and an index can be popped once after one push. Across the whole run the pops total at most n. So the nested loops cost O(n) combined, not n times n.

Asked at

See which companies ask this — Pro

Practise it