A stack is the "last in, first out" (LIFO) collection: push adds to the top, pop removes from the top, peek looks at the top without removing. Exactly three operations, all O(1), all touching the same end. Everything else about the stack follows from that one restriction, and that restriction is precisely what makes it useful.
Why would limiting access be good? Because order of reversal is the stack's nature. The most recent thing pushed is always the first thing popped, which is exactly the behavior of undo (undo your LAST action first), the browser back button (return to the most recent page first), the function call stack (return from the deepest call first), and text editors' bracket matching (match the most recent unmatched opener). Wherever "most recent pending item first" is the rule, a stack is the answer.
| Operation / case | Cost | Notes |
|---|---|---|
| push | O(1) | add at top |
| pop | O(1) | remove from top |
| peek | O(1) | read top without removing |
| isEmpty / size | O(1) | — |
| Search inside | O(n) | stacks don't support it, by design |
Two idiomatic implementations
// 1) Array-backed: push/pop at the END (never shift(), that's O(n))
class ArrayStack {
#items = [];
push(v) { this.#items.push(v); }
pop() { return this.#items.pop(); } // undefined when empty
peek() { return this.#items.at(-1); }
get size() { return this.#items.length; }
isEmpty() { return this.#items.length === 0; }
}
// 2) Linked-node-backed: identical behavior, no dynamic array resizing
class LinkedStack {
#top = null;
#count = 0;
push(v) { this.#top = { value: v, next: this.#top }; this.#count++; }
pop() {
if (!this.#top) return undefined;
const { value, next } = this.#top;
this.#top = next; this.#count--;
return value;
}
peek() { return this.#top?.value; }
}The killer use case: balanced brackets
function isBalanced(s) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const ch of s) {
if (ch === '(' || ch === '[' || ch === '{') {
stack.push(ch); // remember the pending opener
} else if (ch in pairs) {
if (stack.pop() !== pairs[ch]) return false; // must match MOST RECENT opener
}
}
return stack.length === 0; // every opener closed?
}
isBalanced("{[()]}") // true
isBalanced("([)]") // false, ) expects ( on top, finds [