InterviewPrepKit

Home / Coding / Stack

Daily Temperatures

medium Original β†—
Solving tips
  • Recognize the 'next greater element' signature: instead of each day scanning forward, let each new day deliver answers backward via a monotonic decreasing stack.
  • Store indices (not temperatures) on the stack so you can compute the wait as j - i when a warmer day pops an earlier one.
  • Pitfall: 'strictly warmer' means pop on temperatures[top] < temp; using <= mishandles repeated values, and leftover stack indices correctly stay 0.
  • Target O(n) time via amortized push-once/pop-once and O(n) space for the stack.

Problem

You get an array temperatures where entry i is the temperature on day i. For every day, compute how many days you must wait until a strictly warmer day arrives. If no later day is warmer, the answer for that day is 0.

Return the array of wait times (same length as the input).

Examples

  • [73, 74, 75, 71, 69, 72, 76, 73] β†’ [1, 1, 4, 2, 1, 1, 0, 0] β€” e.g. day 2 (75) must wait 4 days for 76; the last two days never see anything warmer.
  • [30, 40, 50, 60] β†’ [1, 1, 1, 0] β€” strictly increasing: always the very next day.
  • [60, 50, 40, 30] β†’ [0, 0, 0, 0] β€” strictly decreasing: never a warmer day.

Constraints

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

n = 10^5 makes the O(n^2) scan-ahead-for-each-day approach about 10^10 comparisons in the worst case β€” the expected solution is O(n).

Think about it first

Hint 1 The nested-loop version wastes work re-scanning the same cold stretch for every day. When day `j` turns out warmer than day `i`, could it answer *several* earlier days at once?
Hint 2 Keep the days that are still waiting for an answer. Notice their temperatures are always in decreasing order β€” if a waiting day were warmer than an earlier waiting day... wait, it would have answered it already. Which structure holds "most recent unanswered first"?
Hint 3 Scan left to right with a stack of indices whose answer is unknown. Each new temperature pops every stack index whose temperature is strictly lower β€” the gap in indices is that day's answer β€” then pushes itself. Whatever remains on the stack at the end gets 0.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.