Skip to content
Algorithms for Beginners

Patterns / Pattern 5 of 5

Stack

Keep the most recent unfinished thing on top, and finish it first.

The 30-second version

Think of a pile of plates: you add to the top and take from the top. Brackets work the same way: in (this [and this]), the last one you opened is the first one you close. A stack keeps track of exactly that.

Stack, in three steps:

  1. Keep a pile (in code, an array).
  2. When something starts, put it on top.
  3. When something ends, take the top off and check they belong together.

Think of it when a problem says:

  • “brackets must match”
  • “undo or backspace”
  • “the next bigger item”
  • “the most recent one first”

That’s the whole idea. The rest of this page shows it working, step by step.

Spot it when: Things must match up in pairs, or you need the next bigger or smaller item.
In one line: Last in, first out: finish the newest thing first.

Words on this page, in plain English (16)Open if any word is new to you
Variable
A labelled box that holds a value. You give it a name, put something in it, and use the name later to get it back.
String
A piece of text, written between quotes. Each letter in it is a character.
Boolean (true or false)
A value that can only be true or false. Like a light switch: on or off.
Array (list)
A list of values kept in order, inside square brackets. Like a row of numbered lockers.
Index (position)
Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.
Length
How many items a list (or letters a string) has. The last position is always length - 1.
If (a decision)
Runs some code only when something is true. Like: if it's raining, take an umbrella.
Loop
Code that repeats. A for loop repeats once per item or a set number of times; a while loop repeats as long as something stays true.
Function
A named, reusable recipe. You give it ingredients (inputs), it does its steps, and hands back a result.
Return
How a function hands back its answer. As soon as return runs, the function stops.
console.log
Prints something so you can see it. The easiest way to find out what your code is really doing.
Template
The usual shape of a pattern's code. You fill in the parts that change for each problem.
O(1): constant time
Takes the same time no matter how big the input is. Like opening a book at page 1.
O(n): linear time
The work grows in step with the input: twice the items, twice the work. One pass.
Stack
A pile where you only touch the top: add with push, take with pop. The last thing in is the first out, like a pile of plates.
Bug, debugging
A bug is a mistake in code. Debugging is finding it, often by printing values with console.log.

Every word, explained simply

A pile of plates

A stack is like a pile of plates: you can only add a plate on top, and only take the top plate off. The last thing you put on is the first thing you take off ("last in, first out").

In JavaScript, a normal array works as a stack:

Try it: an array as a stack

const stack = [];
stack.push("a");   // put on top
stack.push("b");
stack.push("c");
console.log(stack);

console.log(stack.pop()); // take the top off: "c"
console.log(stack[stack.length - 1]); // look at the top without removing it
console.log(stack.length); // how many items

Press Run to see the output. You can change the code first.

push adds to the end of the array and pop removes from the end, both in O(1) time. We just call the end of the array "the top".

Watch it work: the Back button is a stack

history (stack, top first)

  1. empty

last action: –

The browser keeps the pages you've visited on a stack. It starts empty.

Why a stack helps

A stack remembers unfinished business, most recent first. That matches many problems where the latest thing you started is the first thing that must be finished:

  • An opening bracket ( must be closed before the brackets around it are.
  • Pressing Backspace deletes the last character typed.
  • In 3 4 + 2 *, an operator works on the last two numbers you've seen.
  • Going up a folder (..) undoes the last folder you went into.

When you see "the most recent one that hasn't been dealt with yet", think stack.

Race: how much work as the input grows?

Look back over everything O(n²)1,000,000 steps · 10 ms

Keep a stack O(n)1,000 steps · instant

Times assume a fast computer doing about 100 million simple steps a second.

Template: matching pairs

function matches(text) {  const open = [];  for (const char of text) {    if (/* char opens something */) {      open.push(char);    } else if (/* char closes something */) {      if (open.length === 0) return false; // nothing to close      const last = open.pop();      if (/* last doesn't match char */) return false;    }  }  return open.length === 0; // everything opened was closed}

Template: the next bigger item (monotonic stack)

A harder but very useful use: for each item, find the next item to its right that's bigger. Keep a stack of positions still waiting for their answer. When a bigger item arrives, it's the answer for every smaller waiting item on top, so pop them.

function nextBigger(nums) {  const answer = new Array(nums.length).fill(-1);  const waiting = []; // positions, with values getting smaller from bottom to top  for (let i = 0; i < nums.length; i++) {    while (waiting.length > 0 && nums[waiting[waiting.length - 1]] < nums[i]) {      answer[waiting.pop()] = nums[i];    }    waiting.push(i);  }  return answer;}

The stack always stays in decreasing order from bottom to top, which is why it's called a monotonic stack ("monotonic" means always going one way). Each position is pushed once and popped at most once, so it's O(n), even with a loop inside a loop.

When to use it

  • Brackets, tags, or anything that must open and close in order.
  • Undo and backspace: the last action is the first undone.
  • Expressions and calculators.
  • "The next bigger (or smaller) item", "days until warmer": a monotonic stack.

Common mistakes

  • Popping an empty stack. [].pop() gives undefined, not an error, so bugs hide. Check stack.length first.
  • Forgetting what's left at the end. In bracket problems, leftover open brackets mean it's not balanced.
  • Using shift and unshift. They work on the front of the array and move every item, which is O(n). Use push and pop on the end.

Learn it by heart

Understanding a pattern is the first half. The second is being able to write it without looking. Learn the recipe as words first, then each template in four steps. Your results go into your reviews, which bring each one back just before you’d forget it.

The recipe, out loud

  1. Use an array as the stack: push to add on top, pop to take the top.
  2. When something starts (an opener, a waiting item), push it.
  3. When something can finish it, pop and check they belong together.
  4. Each item is pushed and popped at most once, so it's O(n).

Matching pairs

Use it for: Every opener needs its closer, in the right order.

Learn it by heart: Matching pairs

Read the 13 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.

function allClosed(text, opens, closes, belong) {  const open = [];  for (const char of text) {    if (opens(char)) {      open.push(char);    } else if (closes(char)) {      if (open.length === 0) return false;      const last = open.pop();      if (!belong(last, char)) return false;    }  }  return open.length === 0;}

The next bigger item

Use it for: For each item, find the next one that beats it.

Learn it by heart: The next bigger item

Read the 11 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.

function nextBigger(nums) {  const answer = new Array(nums.length).fill(-1);  const waiting = [];  for (let i = 0; i < nums.length; i++) {    while (waiting.length > 0 && nums[waiting[waiting.length - 1]] < nums[i]) {      answer[waiting.pop()] = nums[i];    }    waiting.push(i);  }  return answer;}

Practice problems

Easiest first. Each has hints and a full walkthrough.

SolvedProblemDifficulty
Balanced bracketseasy
Typing with backspaceeasy
Stack with minimummedium
Postfix calculatormedium
Tidy a file pathmedium
Days until warmermedium

More patterns

  • Hashing and counting

    Remember what you have seen in a Map, so you never search for it twice.

  • Two pointers

    Walk through a list from both ends (or at two speeds) at once.

  • Sliding window

    Keep a stretch of the list and slide it along instead of starting over.

  • Binary search

    Halve the search space with every guess.

New to coding? Start with the JavaScript basics, or browse every practice problem.