data structurefree

Stack

A last-in, first-out collection: you only ever touch the top.

time
O(1)
space
O(n)

// step through it

step 1 / 8
1class Stack {2  items = [];3  push(x) {4    this.items.push(x);5  }6  pop() {7    return this.items.pop();8  }9  peek() {10    return this.items[this.items.length - 1];11  }12}
    empty

    Start with an empty stack.

    How it works

    A stack supports push (add on top), pop (remove from the top) and peek (read the top). On a dynamic array all three are O(1). Stacks power undo, function calls, bracket matching and depth-first search.