Data Structures & Algorithms / Module 1: Linear data structures

Topic 1.4

Stack

A pile you can only touch from the top: last in, first out.

8 min · beginner

Watch: the last plate put on is always the first one taken off. Try adding and removing a few plates.

338855STACK · LIFO
Top plate: the only one you can take (peek)The other plates wait underneathA spring-loaded plate dispenser: on every push the platform sinks by one plate, so the top plate always waits at the rim. Pop can only take the top plate. Capacity 8 plates.
peek(): 5

    Like a pile of plates

    In a canteen, clean plates are piled up. New plates go on top, and whoever needs one takes the top plate. Nobody pulls a plate from the middle.

    A stack in a program works exactly like that, with three moves:

    1. push: put one item on top.
    2. pop: take the top item off.
    3. peek: look at the top item without taking it.

    The rule is called LIFO (last in, first out). Try push and pop in the figure. To reach the third plate from the top, the two plates above it have to come off first.

    Why it is fast

    Because every move happens at the top, a bigger pile never makes push or pop slower. Adding the 1,000th plate is as easy as adding the 2nd. In Big-O terms, all three are O(1).

    Code, for programmersIn JavaScript a plain array already works as a stack
    const stack = [];
    stack.push(3);          // [3]
    stack.push(8);          // [3, 8]   8 is on top
    stack.at(-1);           // peek: 8
    stack.pop();            // takes 8, leaves [3]
    stack.length === 0;     // is it empty?

    Where you already use one

    • The undo button. Every change is piled up. Undo reverses the most recent one first.
    • The browser back button. Pages you open pile up; back returns to the last one.
    • Function calls. When function A calls B and B calls C, the computer piles up all three. C finishes first, then B, then A. That pile is the call stack. If a function calls itself forever, the pile fills up: that is the stack overflow error.
    • Checking brackets. Code editors use a stack to know whether every ( has a matching ).

    Try it: check matching brackets

    Every opening bracket goes on the pile. Every closing bracket has to match the bracket on top, and then both are thrown away. If the pile is empty at the end, every bracket had a partner.

    {[()()]}

    stack:

    Press Step to begin.

    Code, for programmersThe code is only a few lines
    function balanced(text) {
      const pairs = { ")": "(", "]": "[", "}": "{" };
      const stack = [];
      for (const ch of text) {
        if ("([{".includes(ch)) stack.push(ch);          // opening: put it on the pile
        else if (ch in pairs) {
          if (stack.pop() !== pairs[ch]) return false;   // closing: must match the top
        }
      }
      return stack.length === 0;                         // nothing left over
    }

    Quiz

    1. A pile holds [1, 2, 3] with 3 on top. After push(4), pop(), pop(), what is left?

    2. A pile holds 1,000 plates. How long does pop() take compared with a pile of 10?

    3. The text "([)]" is checked with a stack. Where does the check fail?

    4. Which feature is the best fit for a stack?

    0 of 4 answered.