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: -1, -1, -1, -1
Top
empty stack
Base
Time
O(n)
Space
O(n)
Step Note
Keep indexes in a decreasing monotonic stack.
function nextGreater(values: number[]) {
const stack = []
const answer = Array(values.length).fill(-1)
for (let i = 0; i < values.length; i++) {
while (stack.length && values[stack.at(-1)] < values[i]) {
answer[stack.pop()] = values[i]
}
stack.push(i)
}
return answer
}