← Index

Linear Structures

Stack

Last In, First Out — only the top is reachable.

What it is

A stack only allows access to the most recently added item. Push adds to the top, pop removes from the top — both O(1). You give up random access entirely in exchange for a very cheap, very predictable operation at one end.

Real-world examples

Where you've probably used this already

Complexity

Push O(1)
Pop O(1)
Peek O(1)
Search O(n)

Code

// Stack — Last In, First Out (LIFO). Think a stack of plates:
// you only ever add or remove from the top.

class Stack {
  constructor() {
    this.items = [];
  }

  push(item) {
    this.items.push(item);
  }

  pop() {
    return this.items.pop();
  }

  peek() {
    return this.items[this.items.length - 1];
  }

  isEmpty() {
    return this.items.length === 0;
  }
}

// --- Example: valid parentheses checker (very common interview question) ---
function isBalanced(str) {
  const stack = new Stack();
  const pairs = { ")": "(", "]": "[", "}": "{" };

  for (const char of str) {
    if (char === "(" || char === "[" || char === "{") {
      stack.push(char);
    } else if (char === ")" || char === "]" || char === "}") {
      if (stack.isEmpty() || stack.pop() !== pairs[char]) return false;
    }
  }
  return stack.isEmpty();
}

// --- Example Usage ---
const s = new Stack();
s.push(1);
s.push(2);
s.push(3);
console.log("Peek:", s.peek()); // 3
console.log("Pop:", s.pop());   // 3
console.log("Peek after pop:", s.peek()); // 2

console.log("isBalanced('({[]})'):", isBalanced("({[]})")); // true
console.log("isBalanced('({[)]}'):", isBalanced("({[)]}")); // false

// Other real uses of this exact pattern:
// - the browser's back button (each page visited gets pushed)
// - undo/redo in an editor
// - the call stack itself (function calls push, returns pop)