I’m solving the daily temperatures problem with a monotonic stack, but this version returns values that are too large for some indices. I expected [1,1,4,2,1,1,0,0] for the sample, but I’m getting incorrect gaps around the middle. What is wrong with the stack logic here?
function dailyTemperatures(t) {
const res = Array(t.length).fill(0), st = [];
for (let i = 0; i < t.length; i++) {
while (st.length && t[i] > t[st[st.length - 1]]) {
const idx = st.pop();
res[idx] = i;
}
st.push(i);
}
return res;
}
Quelly ![]()