InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Stack

Daily Temperatures

medium Original ↗ 00:00

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 re-scans the same falling stretch for every day. When day `j` turns out warmer than day `i`, can it answer several earlier days at once?
Hint 2 Track the days still waiting for an answer. Their temperatures are always in decreasing order: a waiting day warmer than an earlier one would already have answered it. Which structure returns the most recent unanswered day first?
Hint 3 Scan left to right with a stack of indices whose answer is unknown. Each new temperature pops every stack index with a strictly lower temperature (the index gap is that day's answer), then pushes itself. Indices left on the stack at the end keep 0.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug