KatInterview

Days Until Higher Temperature

Stacks & QueuesAuto-graded · 26 test cases
MediumAuto-gradedStacks & Queuesmonotonic-stacknext-greater-elementarrays

Last updated

Tests efficient computation of the distance to the next strictly greater element using a monotonic stack to achieve linear time complexity.

You are given an array of integers temperatures where each element represents the temperature recorded on a particular day.

For each day in the array, determine how many days into the future you must look to find a strictly higher temperature. If no such day exists, the result for that position should be 0.

Return an array of integers where each element represents the number of days to wait for a warmer temperature from the corresponding day in the input.

Constraints

  • 1 <= len(temperatures) <= 10^5
  • 30 <= temperatures[i] <= 100
  • Equal temperatures do not count as "warmer" — you must find a strictly greater value

Examples

Example 1

Input: days_until_warmer([73, 74, 75, 71, 69, 72, 76, 73])

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

Example 2

Input: days_until_warmer([30, 40, 50, 60])

Output: [1, 1, 1, 0]

Example 3

Input: days_until_warmer([90, 80, 70])

Output: [0, 0, 0]

Hints

Hint 1

Think about what information you need to track as you scan through the array from left to right.

Hint 2

A stack can help you keep track of days that haven't yet found their warmer day. What should you store in the stack?

Hint 3

When you encounter a new temperature, it might resolve multiple previous days at once. How can you efficiently find all the days it resolves?