Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Stack

Days until a warmer day

Medium · Target 15 minutes · Stack· Type asked at

Given an array temps of daily temperatures, return an array wait of the same length where wait[i] is the number of days after day i until a strictly warmer day. If no later day is warmer, wait[i] is 0.

Examples

InputOutputWhy
temps = [73, 74, 75, 71, 69, 72, 76, 73][1, 1, 4, 2, 1, 1, 0, 0]Day 2 (75) waits four days, until 76 on day 6.
temps = [30, 40, 50, 60][1, 1, 1, 0]Rising every day: each day waits one.
temps = [50, 50, 50, 51][3, 2, 1, 0]An equal temperature is not warmer.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 30 ≤ temps[i] ≤ 100

Hints

Hint 1

The direct approach scans forward from every day for the first warmer one. What is its worst case, and on what input?

Hint 2

When a warm day arrives, which earlier days does it settle? Only days that are still waiting, and only those cooler than it.

Hint 3

Keep the indices of days still waiting on a stack. Their temperatures never increase from bottom to top. A new day pops every waiting day cooler than itself, records the gap for each, then waits itself.

Where people lose marks

  • Pushing temperatures instead of indices. You need the index to compute the gap, and you can always look the temperature up from it.
  • Popping on <= instead of <. An equal temperature is not warmer, so [50, 50, 51] would wrongly give the first day an answer of 1.
  • Assuming the answers come out in index order. They are filled in whenever a day is popped, so write into a pre-sized array rather than appending.
  • Worrying that days left on the stack need special handling. They never saw a warmer day, and the array was initialised to 0, which is the right answer for them.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.