Skip to content
Problem 739 · LeetCode 739(opens in a new tab)

Daily Temperatures

MediumArrays

You get a list of daily temperatures, temperatures, one number per day in order. For every day, work out how many days you would have to wait after it until a day that is strictly warmer.

Return a list answer of the same length, where answer[i] is that wait for day i. If no later day is warmer, answer[i] is 0.

Example 1

Input:  temperatures = [70, 68, 72, 69, 75, 71]
Output: [2, 1, 2, 1, 0, 0]
Why:    70 waits two days for 72; 75 and 71 never see warmer
2 more examples and the constraints

Example 2

Input:  temperatures = [50, 50, 50]
Output: [0, 0, 0]
Why:    an equal day is not a warmer day

Example 3

Input:  temperatures = [90, 80, 70, 60, 95]
Output: [4, 3, 2, 1, 0]
Why:    every day waits for the 95 at the end

Constraints

  • 1 ≤ length of temperatures ≤ 100,000
  • 30 ≤ each temperature ≤ 100

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Scan aheadO(n²)
  2. Monotonic stackO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 daysVerdict
Scan aheadO(n²)
Correct, too slow on long cold runs
Monotonic stackO(n)
Best; each day in and out once

n = number of days.

Edge cases to test

  • One day. [30] has nothing after it, so the answer is [0].
  • Equal temperatures. [50, 50, 50] gives [0, 0, 0]: the comparison must be strictly warmer.
  • Falling all the way. [100, 90, 80] never pops, so the whole list stays on the stack and every answer is 0.
  • One hot day at the end. [90, 80, 70, 60, 95]: one push pops four days in a row.

Common mistakes

  • Popping on <= instead of <, so an equal day counts as warmer.
  • Storing temperatures on the stack instead of indices, which loses the day you need to compute the wait.
  • Writing the answer for today when you push it, instead of for the day you pop.

How to talk through it

  1. 1Clarify. Does an equal temperature count as warmer? What goes in the answer when no warmer day comes?
  2. 2Give the brute force. Scan forward from each day; say it is O(n²) and show the cold-run input that makes it slow.
  3. 3Turn it around. Let each new day answer the earlier days that were waiting for it. The waiting days form a stack that only falls.
  4. 4Code the stack. Store indices, pop while the top is colder, then push. Explain why each index moves at most twice.
  5. 5Test out loud. Run the equal-temperatures case and the one-hot-day-at-the-end case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?