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