Stacks And Queues
Stack Operations
Visualize LIFO behavior with push, pop, and peek operations before moving into parentheses parsing and monotonic stack patterns.
O(n) time / O(n) space
LIFO: last in, first outoperation: monotonicresult: 0, 0, 0, 0
Top
empty stack
Base
Time
O(n)
Space
O(n)
Step Note
Use a decreasing stack of day indexes waiting for warmer temperatures.
function dailyTemperatures(values: number[]) {
const stack = []
const waits = Array(values.length).fill(0)
for (let day = 0; day < values.length; day++) {
while (stack.length && values[stack.at(-1)] < values[day]) {
const previous = stack.pop()
waits[previous] = day - previous
}
stack.push(day)
}
return waits
}