Stack
A last-in, first-out collection: push onto the top, pop from the top, both O(1). Behind function calls, undo, parsing and depth-first search.
Description
A stack works like a pile of plates: you add to the top (push) and take from the top (pop). The last item in is the first out, LIFO. You can usually also peek at the top without removing it.
Stacks are everywhere once you look. The call stack stores each function's local state while it calls another. Undo in an editor pops the most recent change. Parsers use stacks to match brackets and evaluate expressions. Depth-first search uses a stack, explicitly or through recursion, to remember where to backtrack to.
A stack is simple to implement on top of a dynamic array (push and pop at the end) or a linked list (push and pop at the head). Both give O(1) operations.
How it works
A stack stored in an array: the top is the last element
- index 0: 3
- index 1: 7
- index 2: 1
- index 3: 9
Complexity
| Operation | Average | Worst |
|---|---|---|
| PushAmortized O(1) on a dynamic array. | O(1) | O(n) |
| Pop | O(1) | O(1) |
| Peek | O(1) | O(1) |
| SearchStacks aren't meant for searching. | O(n) | O(n) |
Space: O(n)
TypeScript implementation
A stack on a JavaScript array, used to check balanced brackets, a classic stack problem.
// A stack on top of a JavaScript array (push and pop at the end are O(1)),
// used to check whether brackets in a string are balanced.
export class Stack<T> {
private items: T[] = [];
push(value: T): void {
this.items.push(value);
}
pop(): T | undefined {
return this.items.pop();
}
peek(): T | undefined {
return this.items[this.items.length - 1];
}
get size(): number {
return this.items.length;
}
}
const PAIRS: Record<string, string> = { ")": "(", "]": "[", "}": "{" };
export function isBalanced(text: string): boolean {
const stack = new Stack<string>();
for (const ch of text) {
if (ch === "(" || ch === "[" || ch === "{") stack.push(ch);
else if (ch in PAIRS) {
if (stack.pop() !== PAIRS[ch]) return false; // wrong closer, or nothing open
}
}
return stack.size === 0; // anything left open is unbalanced
}
export function demo(): string[] {
return ["{ a: [1, (2 + 3)] }", "(a[b)c]", "((x)", "f(g[h{}])"].map((s) => `${s.padEnd(20)} balanced: ${isBalanced(s)}`);
}When to use it
Use it when
- You need to undo or backtrack: editors, navigation, search algorithms.
- Matching nested structures: brackets, HTML tags, expression parsing.
- Replacing recursion with an explicit stack to avoid stack overflows on deep inputs.
Avoid it when
- Items should be processed in arrival order: use a queue.
- You need the highest-priority item rather than the latest: use a binary heap.
- You need access to items in the middle.
Pitfalls
- Popping an empty stack, which returns undefined or throws. Check the size first.
- Stack overflow from deep recursion, which is the call stack running out of space. Convert to an explicit stack.
- Using
shift/unshifton an array-backed stack, which makes operations O(n). Push and pop at the end.
Alternatives
Queue or deque
Choose it when you need first-in, first-out order, or both ends.
Binary heap
Choose it when you always need the highest-priority item next.