Introduction
The Daily Temperatures problem involves finding how many days must pass until a warmer temperature occurs.
Given an array:
temperatures[i] the task is to:
- find the number of days
until a warmer temperature appears
If no warmer day exists:
- return 0
This problem is one of the most important applications of:
Monotonic Stack This problem helps in understanding:
- stack optimization
- next greater patterns
- linear traversal
- efficient searching
Example
Input:temperatures =
[73,74,75,71,69,72,76,73]
Output:
[1,1,4,2,1,1,0,0]
Explanation:
73 → warmer after 1 day
74 → warmer after 1 day
75 → warmer after 4 days 76 → no warmer day
Constraints
1 <= temperatures.length <= 10^530 <= temperatures[i] <= 100Approach 1 : Brute Force Traversal
Explanation
The simplest way is:
- Traverse every day
- Search future days
- Find first warmer temperature
This works but repeated searching becomes inefficient.
Steps
- Traverse temperatures.
- Search future warmer day.
- Store waiting days.
- Return result array.
Dry Run
Input:[73,74,75,71,69,72,76,73]
For 73:
74 is warmer after 1 day
For 75: 76 is warmer after 4 days
For 76: No warmer day
Result: [1,1,4,2,1,1,0,0]
Brute Force Code
Complexity Analysis
Time Complexity: O(n²)
Explanation:
Future days are repeatedly searched.
Space Complexity: O(1)
Explanation:
Only output array is used.Approach 2 : Monotonic Stack
Explanation
The optimized solution uses:
Monotonic Decreasing StackIdea:
- stack stores indices
of decreasing temperatures - whenever warmer temperature appears:
- resolve previous colder days
Process:
- Traverse array
- Remove smaller temperatures
- Calculate waiting days
- Push current index
This avoids repeated searching.
Steps
- Create stack.
- Traverse temperatures.
- Resolve colder days.
- Store waiting days.
- Push current index.
Dry Run
Input:[73,74,75,71]
Stack:
[]
73 pushed
Stack:
[0]
74 warmer than 73
Result[0] = 1
75 warmer than 74
Result[1] = 1
71 pushed
Final Result: [1,1,0,0]
Monotonic Stack Code
Complexity Analysis
Time Complexity: O(n)
Explanation:
Each index is pushed and popped once.
Space Complexity: O(n)
Explanation:
Stack stores indices.