Skip to main content
Beginner ~10 min read

Stacks

Last-in, first-out: push, pop, peek. The structure behind undo, browser back, function calls, and expression parsing.

Prerequisites: Arrays: Traversal, Insertion & Deletion

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 / caseCostNotes
pushO(1)add at top
popO(1)remove from top
peekO(1)read top without removing
isEmpty / sizeO(1)—
Search insideO(n)stacks don't support it, by design

Two idiomatic implementations

stack.js
// 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

brackets.js
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 [

Check your understanding

  1. 1.push(1), push(2), push(3), pop(), push(4), pop(), pop(). What does the final pop return?
  2. 2.Which feature is NOT naturally a stack?
  3. 3.In isBalanced, why does pop() compare against the most recent opener?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Visualize it

Stack Operations

Play, pause, and scrub the real algorithm step by step.

Play it

Stack & Queue Puzzle

Hit exact pop and dequeue targets using LIFO and FIFO logic. Popping the wrong item teaches you the hard way w…

Keep going