Daily Temperature Warmer
You are given an array of integers representing daily temperatures. For each day, find how many days you would need to wait until a warmer temperature appears. If there is no warmer day in the future, the answer for that day is 0.
For example, given [73, 74, 75, 71, 69, 72, 76, 73], the answer is [1, 1, 4, 2, 1, 1, 0, 0]. Day 0 (73 degrees) warms up to 74 on day 1, so the wait is 1 day. Day 2 (75 degrees) does not warm up until day 6 (76 degrees), which is 4 days later. The last two days have no warmer future, so their answers are 0.
The brute force approach checks every pair of days using nested loops, running in O(n²). A monotonic decreasing stack solves it in O(n) by tracking unresolved days. As you iterate through the temperatures, the stack holds indices of days that have not yet found a warmer temperature. When the current temperature is warmer than the temperature at the index on top of the stack, you pop the stack and calculate the difference in days.
This is the same pattern as the Next Greater Element problem, but instead of returning the greater value, you return the index distance. The stack remains decreasing (or equal) because if a temperature is not warmer than the top, it is pushed and will be resolved by a future warmer day.
An empty stack means no days are waiting for a warmer temperature. At the end of the iteration, all indices remaining in the stack have no warmer future day, so their answer stays at the initialized value of 0.
Example Input & Output
Each day warms up the next day except the last.
No warmer day exists for any day because all temperatures are equal.
Day 0 (73) warms up to 74 on day 1. Day 2 (75) warms up to 76 on day 6, 4 days later.
Algorithm Flow

Solution Approach
Iterate through temperatures. For each temperature, while the stack is not empty and the current temperature is greater than the temperature at the index on top of the stack, pop the index and set answer[popped] = currentIndex - poppedIndex. Push the current index onto the stack. Remaining indices in the stack have no warmer future day, so their answer stays 0.
Time and space complexity are O(n).
Best Answers
import java.util.*;
class Solution {
public int[] solution(int[] temperatures) {
int n = temperatures.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
int idx = stack.pop();
result[idx] = i - idx;
}
stack.push(i);
}
return result;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
