Chapter 5 · Linear Structures

Stacks

Last In, First Out. The simplest constraint you can add to a list — yet it powers your programming language's function calls, your browser's back button, your editor's undo history, and every recursive algorithm ever written.

What is a stack data structure?

A stack is a Last In, First Out (LIFO) collection: you push items onto the top and pop them off the top, like a stack of plates. Push, pop and peek are all O(1). Stacks power function calls (the call stack), undo history, the browser's back button, bracket matching and depth-first search.

const stack = [];
stack.push(1); stack.push(2);   // [1, 2]
stack.at(-1);                   // peek → 2
stack.pop();                    // 2

function isBalanced(s) {        // classic: matching brackets
  const pairs = { ")": "(", "]": "[", "}": "{" }, st = [];
  for (const ch of s) {
    if ("([{".includes(ch)) st.push(ch);
    else if (pairs[ch] && st.pop() !== pairs[ch]) return false;
  }
  return st.length === 0;
}

The physical model

Picture a stack of dinner plates. You always add to the top and take from the top. There's no accessing the bottom plate without first removing every plate above it. This single constraint — only interact with the top — is the entire definition of a stack.

Plates

Plate Stack

Add and remove only from the top of a stack of plates.

fn()

Function calls

The most recent function call is always resolved first.

Ctrl+Z

Undo history

The most recent edit is always undone first.

Live call stack demo

This simulates what your language runtime does on every function call. Push adds a new frame on top. Pop removes the topmost frame — just like a function returning to its caller.

Stack — LIFO
size: 4isEmpty: falsetop: 5
push direction
03
17
212
35TOP
pop direction

Operations

Log

▶ Stack initialized with [3, 7, 12, 5]

Interactive sandbox — code a Stack

Now it's your turn. Implement a dynamic Stack in JavaScript and use it to validate whether brackets inside an expression are nested correctly. Edit the code below and run it live!

Code Editor

<button id="push">push</button> <button id="pop">pop</button> <button id="peek">peek</button>
<div id="stack"></div>
<p id="out"></p>

Preview

Implementation with a dynamic array

A stack is just a dynamic array with a rule: only touch the last element. No separate data structure is needed.

stack.pseudo
1Stack uses a dynamic array internally
2 
3push(value):
4 array.append(value) // O(1) amortised
5 top <- last element
6 
7pop():
8 if isEmpty(): error
9 value <- array[last]
10 array.removeLast() // O(1)
11 return value
12 
13peek():
14 if isEmpty(): error
15 return array[last] // O(1), no removal
16 
17isEmpty():
18 return array.length = 0

How the call stack actually works

Every time your program calls a function, the runtime pushes a stack frameonto the call stack. Each frame stores the function's local variables, parameters, and the return address. When the function returns, its frame is popped and execution continues exactly where it left off.

1

main() calls compute(5)

Frame for compute(5) pushed onto call stack. main() pauses.

► compute(5)
main()

↑ top of stack

2

compute() calls helper(5)

Frame for helper(5) pushed. compute() pauses. Stack now has 3 frames.

► helper(5)
compute(5)
main()

↑ top of stack

3

helper() returns 25

helper's frame popped. Execution resumes in compute() with return value 25.

► compute(5)
main()

↑ top of stack

4

compute() returns 30, main() finishes

compute's frame popped, then main's. Stack empty. Program ends.

stack empty

Classic stack algorithms

Balanced parentheses

Push opening brackets. On every closing bracket, pop and verify it matches. If the stack is empty at the end, brackets are balanced. Compilers use this exact algorithm.

Undo / Redo

Maintain two stacks: undoStack and redoStack. Every action is pushed to undoStack. Undo pops from undoStack and pushes to redoStack. Redo reverses this.

Browser history

Navigating to a new page pushes it onto the back-stack. The Back button pops from back-stack and pushes to forward-stack. Forward pops from forward-stack.

Expression evaluation

Parse arithmetic left-to-right. Numbers go to an operand stack. Operators go to an operator stack. When an operator of lower/equal precedence arrives, pop and evaluate.

Time complexity

Push (add to top)O(1)

Constant time

Pop (remove from top)O(1)

Constant time

Peek (read top without removing)O(1)

Constant time

Search (stacks are not designed for search)O(n)

Linear time

⚠️What is a stack overflow?
A stack overflow happens when the call stack exceeds its memory limit. Infinite recursion is the most common cause: a function keeps calling itself, pushing frames forever until the runtime runs out of stack space and crashes. The limit is typically 1,000-10,000 frames depending on the language and platform. Always ensure recursive functions have a correct base case.

🎯 Quick Check

You push A, then B, then C onto a stack. You then call pop() twice. What is now on top?

🧠The one-line definition
A stack is a list with a single rule: only the last item added can be removed. That constraint alone makes it the right tool for any problem involving “most recent first” semantics.

Stacks: summary

Key points

  • A JavaScript array with push and pop is a perfectly good stack.
  • Recursion uses the call stack implicitly; you can convert recursion to a loop with an explicit stack.
  • "Stack overflow" means the call stack ran out of space.

Frequently asked questions

›What is the difference between a stack and a queue?

A stack is LIFO (the last item added comes out first). A queue is FIFO (the first item added comes out first).

›Where are stacks used in real life?

Undo/redo, browser back navigation, expression evaluation, syntax checking in compilers, and depth-first search.