Stacks and Queues
A stack is Last In, First Out (LIFO), like a stack of plates: you add and remove from the top. A queue is First In, First Out (FIFO), like a line at a store. Stacks power undo buttons and the call stack; queues are used for tasks waiting their turn.
// Stack
const stack: number[] = []
stack.push(1)
stack.push(2)
stack.pop() // 2 (last in, first out)
// Queue
const queue: number[] = []
queue.push(1)
queue.push(2)
queue.shift() // 1 (first in, first out)
// Classic stack problem: balanced brackets
function isBalanced(s: string) {
const pairs: Record<string, string> = { ")": "(", "]": "[", "}": "{" }
const st: string[] = []
for (const ch of s) {
if ("([{".includes(ch)) st.push(ch)
else if (pairs[ch] && st.pop() !== pairs[ch]) return false
}
return st.length === 0
}