Skip to the content

Lesson 128 of 296

Stacks

What you will learn

  • What a stack is (LIFO)
  • Stacks in JavaScript
  • Valid Parentheses
  • Min Stack
  • Evaluate Reverse Polish Notation
On this page

What is a stack?

A stack is a collection where you can only add or remove at one end, the top. The last item added is the first removed: LIFO (Last In, First Out). Think of a stack of plates.

OperationMeaningCost
pushAdd to the topO(1)
popRemove from the topO(1)
peekLook at the top without removingO(1)

In JavaScript, an array is a perfect stack: push, pop and at(-1) are all O(1).

Where stacks appear: the call stack (Lesson 68), undo history, the browser back button, matching brackets, evaluating expressions, depth-first search (Lesson 136).

Valid Parentheses

Problem (LeetCode 20): is a string of ()[]{} brackets correctly matched and nested?
"([]{})" → true. "(]" → false. "((" → false.

Idea: push each opening bracket. For a closing bracket, the most recent unmatched opening bracket (the top of the stack) must be its pair.

TypeScript
function isValidParentheses(s: string): boolean {
  const pairs: Record<string, string> = { ")": "(", "]": "[", "}": "{" };
  const stack: string[] = [];
  for (const ch of s) {
    if (ch === "(" || ch === "[" || ch === "{") {
      stack.push(ch);
    } else {
      if (stack.pop() !== pairs[ch]) return false;
    }
  }
  return stack.length === 0;
}
  • stack.pop() on an empty stack returns undefined, which never matches, so a closing bracket with nothing open fails correctly.
  • At the end, the stack must be empty, or some brackets were never closed.

O(n) time, O(n) space.

Min Stack

Problem (LeetCode 155): design a stack with push, pop, top and getMin, all O(1).

Idea: keep a second stack where each position stores the minimum so far at that height. When you pop, both stacks pop, so the minimum is always correct.

TypeScript
class MinStack {
  private items: number[] = [];
  private mins: number[] = [];

  push(val: number): void {
    this.items.push(val);
    const currentMin = this.mins.length === 0 ? val : Math.min(val, this.mins.at(-1)!);
    this.mins.push(currentMin);
  }

  pop(): void {
    this.items.pop();
    this.mins.pop();
  }

  top(): number | undefined {
    return this.items.at(-1);
  }

  getMin(): number | undefined {
    return this.mins.at(-1);
  }
}
ActionitemsminsgetMin
push 5[5][5]5
push 3[5, 3][5, 3]3
push 7[5, 3, 7][5, 3, 3]3
pop[5, 3][5, 3]3
pop[5][5]5

O(1) for every operation, O(n) extra space.

Evaluate Reverse Polish Notation

Problem (LeetCode 150): evaluate an expression written in Reverse Polish Notation (operators come after their numbers).
["2", "1", "+", "3", "*"] means (2 + 1) * 3 = 9.

Idea: push numbers. On an operator, pop two numbers, apply it, push the result. Order matters: the second pop is the left operand.

TypeScript
function evalRPN(tokens: string[]): number {
  const stack: number[] = [];
  for (const token of tokens) {
    if (token === "+" || token === "-" || token === "*" || token === "/") {
      const right = stack.pop()!;
      const left = stack.pop()!;
      if (token === "+") stack.push(left + right);
      else if (token === "-") stack.push(left - right);
      else if (token === "*") stack.push(left * right);
      else stack.push(Math.trunc(left / right));
    } else {
      stack.push(Number(token));
    }
  }
  return stack.pop()!;
}

Math.trunc because the problem says division truncates towards zero (-7 / 2 is -3, not -4, which Math.floor would give).

O(n) time, O(n) space.

Other stack problems to practise

  • Decode String ("3[a2[c]]" → "accaccacc")
  • Simplify Path (Unix paths with .. and .)
  • Basic Calculator
  • Asteroid Collision

How to say it in an interview

"A stack is LIFO with O(1) push, pop and peek, and in JavaScript a plain array works. I reach for one when I need the most recent unmatched item: for valid parentheses I push openers and check each closer against the top, then require an empty stack. Min Stack keeps a parallel stack of running minimums so getMin is O(1). Reverse Polish Notation pushes numbers and, on an operator, pops right then left operands."

Key words

WordMeaning
StackA collection with add and remove at one end
LIFOLast in, first out
Push / pop / peekAdd / remove / look at the top
Reverse Polish NotationWriting operators after their operands

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.