Imagine you're a weather forecaster tasked with helping people plan their activities. Given an array of daily temperatures, you need to determine how many days each person must wait to experience a warmer day.
For each day i, calculate the number of days until a temperature higher than temperatures[i] occurs. If no warmer day exists in the future, return 0 for that day.
Example: If temperatures are [73, 74, 75, 71, 69, 72, 76, 73], then:
- Day 0 (73°): Next warmer day is day 1 (74°) → wait 1 day
- Day 1 (74°): Next warmer day is day 2 (75°) → wait 1 day
- Day 5 (72°): Next warmer day is day 6 (76°) → wait 1 day
This is a classic "next greater element" problem that can be solved efficiently using a monotonic stack.
Input & Output
Visualization
Time & Space Complexity
Each element is pushed and popped from stack at most once, resulting in linear time
In worst case (decreasing temperatures), stack can contain all n elements
Constraints
- 1 ≤ temperatures.length ≤ 105
- 30 ≤ temperatures[i] ≤ 100
- All temperatures are valid Fahrenheit temperatures