1. Index stack
The stack holds indices waiting for a warmer day.
const stack = []Typorithm · medium
Step 1 of 8 · intro card
Stacks & Queues
Keep a stack of indices with decreasing temperatures; a warmer day resolves all cooler ones below it.
Each day needs the distance to the next warmer day, a next-greater-element problem.
A monotonic stack of indices holds days still waiting for something warmer.
When today is warmer, it pops and resolves every cooler day, recording the index gap.
Stack holds waiting indices.
Warmer day resolves cooler ones.
Answer is the index gap.
function dailyTemperatures(temps) {
const result = new Array(temps.length).fill(0);
const stack = [];
for (let i = 0; i < temps.length; i += 1) {
while (stack.length > 0 && temps[i] > temps[stack[stack.length - 1]]) {
const prev = stack.pop();
result[prev] = i - prev;
}
stack.push(i);
}
return result;
}Connect each part of the code to the concept before you type.
The stack holds indices waiting for a warmer day.
const stack = []Today resolves every cooler day still on the stack.
while (stack.length > 0 && temps[i] > temps[stack[stack.length - 1]])The gap in indices is the days until a warmer temperature.
result[prev] = i - prevToday's index waits until a warmer day appears.
stack.push(i)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.