32. Daily Temperatures
For each day, how many days do you have to wait until a warmer temperature? Use 0 if no warmer day follows.
Example 1
Input:
temperatures = [30,38,32,35,40,31]Output:
[1,3,1,1,0,0]Example 2
Input:
temperatures = [50,50,50]Output:
[0,0,0]Hint 1
This is the “next greater element” pattern.
Hint 2
Keep a stack of days that have not found a warmer day yet; their temperatures are decreasing.
Approach 1: Scan forward for each day
For each day look ahead until warmer.
⏱ Time O(n²)💾 Space O(1)
Approach 2: Monotonic stack ✅
Each index is pushed and popped once.
⏱ Time O(n)💾 Space O(n)
Reference solution for Monotonic stack (time O(n), space O(n)). Each solution passes every test in all four languages.
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
res = [0] * len(temperatures)
stack = [] # indices of days still waiting, temps decreasing
for i, t in enumerate(temperatures):
while stack and temperatures[stack[-1]] < t:
j = stack.pop() # day j finally found a warmer day
res[j] = i - j
stack.append(i)
return resclass Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] res = new int[temperatures.length];
Deque<Integer> stack = new ArrayDeque<>(); // indices waiting for a warmer day
for (int i = 0; i < temperatures.length; i++) {
while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) {
int j = stack.pop();
res[j] = i - j;
}
stack.push(i);
}
return res;
}
}class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
vector<int> res(temperatures.size(), 0), st; // st: indices waiting for a warmer day
for (int i = 0; i < (int)temperatures.size(); i++) {
while (!st.empty() && temperatures[st.back()] < temperatures[i]) {
res[st.back()] = i - st.back();
st.pop_back();
}
st.push_back(i);
}
return res;
}
};function dailyTemperatures(temperatures) {
const res = new Array(temperatures.length).fill(0), stack = []; // indices waiting for a warmer day
for (let i = 0; i < temperatures.length; i++) {
while (stack.length && temperatures[stack[stack.length - 1]] < temperatures[i]) {
const j = stack.pop();
res[j] = i - j;
}
stack.push(i);
}
return res;
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
Watch the core idea of this problem step by step. Change the input and press Visualize.
Explained in the lesson Stacks, Queues & Monotonic Stacks.
Run your code to see results here.