Daily Temperatures

35 min · dailyTemperatures()

Knowing that warmer weather is coming isn't enough — you want to know exactly how long you'll wait.

You're given an integer array temperatures, where each value records one day's temperature. Return an array waits of the same length. For each day i, waits[i] must be the number of days until the first later day with a strictly higher temperature. Use 0 when no warmer day follows.

A few ground rules:

  • Equal temperatures aren't warmer.
  • You want the first warmer day, not the warmest future day.
  • The last day always receives 0 because no day follows it.

Constraints

  • 1 <= temperatures.length <= 100_000
  • -100 <= temperatures[i] <= 100

Hints

Start with the direct question

For each day, scan forward until you find a higher temperature. This is correct. Count the comparisons for 100,000 equal days before deciding it's fast enough.

Keep only unresolved days

As you move forward, some earlier days still haven't seen anything warmer. When today's temperature beats one of them, today's index immediately gives its wait.

Make the newest day easy to check

A monotonic stack stores items in a maintained order. Keep unresolved day indices so their temperatures run from hotter to cooler toward the top. Pop while today is warmer, recording today - earlier for every popped index.

Follow-up

If temperatures arrived one day at a time, which answers could you emit immediately, and which days would still need to wait on your stack?

Visible cases

Examples

Example 1

ready
Input
temperatures = [
  73,
  74,
  75,
  71,
  69,
  72,
  76,
  73
]
Expected
[
  1,
  1,
  4,
  2,
  1,
  1,
  0,
  0
]
Why
each value counts forward to its first strictly warmer day

Example 2

ready
Input
temperatures = [
  30,
  40,
  50,
  60
]
Expected
[
  1,
  1,
  1,
  0
]
Why
every day except the last is followed immediately by a warmer one

Example 3

ready
Input
temperatures = [
  90,
  80,
  70
]
Expected
[
  0,
  0,
  0
]
Why
a falling forecast never produces a warmer future day

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite