Days Until a Warmer Day
Problem
Given an array of daily temperatures, return for each day the number of days you must wait until a strictly warmer day occurs. If there is no future warmer day, write 0. Walk left to right with a stack of indices whose answers are still pending.
Input
temps = [70, 73, 71, 75, 69, 72]Output
[1, 2, 1, 0, 1, 0]Day 0 (70) → next warmer is day 1 (73), wait 1. Day 3 (75) has no warmer day after it, so 0.
def daily_wait(temps):
ans = [0] * len(temps)
stack = []
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
j = stack.pop()
ans[j] = i - j
stack.append(i)
return ans
function dailyWait(temps) {
const ans = new Array(temps.length).fill(0);
const stack = [];
for (let i = 0; i < temps.length; i++) {
while (stack.length && temps[stack[stack.length - 1]] < temps[i]) {
const j = stack.pop();
ans[j] = i - j;
}
stack.push(i);
}
return ans;
}
class Solution {
public int[] dailyWait(int[] temps) {
int[] ans = new int[temps.length];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < temps.length; i++) {
while (!stack.isEmpty() && temps[stack.peek()] < temps[i]) {
int j = stack.pop();
ans[j] = i - j;
}
stack.push(i);
}
return ans;
}
}
vector<int> dailyWait(vector<int>& temps) {
vector<int> ans(temps.size(), 0);
stack<int> st;
for (int i = 0; i < (int)temps.size(); i++) {
while (!st.empty() && temps[st.top()] < temps[i]) {
int j = st.top(); st.pop();
ans[j] = i - j;
}
st.push(i);
}
return ans;
}