Algorithm Day73 - Daily Temperatures
π§© Problem Description
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the i-th day to get a warmer temperature.
If there is no future day for which this is possible, keep answer[i] == 0 instead.
π¬ Examples
Example 1
1 | Input: temperatures = [73,74,75,71,69,72,76,73] |
Example 2
1 | Input: temperatures = [30,40,50,60] |
Example 3
1 | Input: temperatures = [30,60,90] |
π‘ Intuition
We can use a monotonic decreasing stack to keep track of temperatures indices:
- Iterate through the array.
- For each day, check if current temperature is higher than the one on top of the stack.
- If yes, pop the index and calculate the difference in days.
- Push the current index onto the stack.
π’ Java Code (Monotonic Stack)
1 | import java.util.*; |
β± Complexity Analysis
- Time: O(n) β each element pushed and popped at most once.
- Space: O(n) β stack storage.
βοΈ Summary
- Use monotonic decreasing stack to track indices of temperatures.
- For each warmer day, update result for all previous colder days.
Related problems
lc-496β Next Greater Element Ilc-503β Next Greater Element IIlc-42β Trapping Rain Water