KatInterview

Next Warmer Day in a Temperature Log

Stacks & QueuesAuto-graded · 17 test cases
EasyAuto-gradedStacks & Queuesstackmonotonic stackarray

Last updated

Tests the ability to use a monotonic stack to efficiently find, for each day, how many days until a strictly warmer temperature is recorded.

Next Warmer Day in a Temperature Log

A weather station recorded daily high temperatures as a list of integers. For each day, you want to know how many days you have to wait until a day with a strictly higher temperature occurs.

If no such future day exists, the answer for that day is 0.

Given a list temps of n daily temperatures, return a list result of the same length where result[i] is the number of days after day i until a strictly warmer day, or 0 if no such day exists.

Constraints

  • 1 ≤ len(temps) ≤ 2000
  • -50 ≤ temps[i] ≤ 50
  • Temperatures are integers.
  • The last element always gets answer 0 (no future day exists).
  • Equal temperatures do not count as warmer.

Examples

Example 1

Input: next_warmer_day([30, 28, 32, 25, 35, 29])

Output: [2, 1, 2, 1, 0, 0]

Example 2

Input: next_warmer_day([20, 20, 20, 20])

Output: [0, 0, 0, 0]

Example 3

Input: next_warmer_day([15])

Output: [0]

Hints

Hint 1

Think about what information you need when you finally find a warmer day for a previous day — you need to know the index of that earlier day.

Hint 2

A stack that keeps indices of days whose 'next warmer day' hasn't been found yet is useful. What ordering property should those indices have with respect to their temperatures?

Hint 3

Maintain a stack of indices with non-increasing temperatures. When you encounter a day warmer than the top of the stack, you've found the answer for that top index: pop it, compute the difference, and repeat.