AlgoViz

Stack

easy 14 min

A stack is a linear data structure where items are added and removed at the same end, the top.

Video lesson · Chapter 1 of 6

The bottom tray is trapped

0:00 / 5:06

Stack of Trays — Stack

1:23Reel

Read caption

Try grabbing the bottom tray. You can reach it only after lifting the ones above it. Push C, A, T. Peek and you'll see T with all three trays still in place. Pop them and the letters come out T, A, C. The same last-in, first-out rule reverses the word in code.

How it works

Step through the idea, or press Play.

Step 1 of 3

Push onto the top. A new item always goes on top of the pile, never in the middle or at the bottom

Understand it

Start here

What a stack is

A stack is a linear data structure where items are added and removed at the same end, called the top. The last item in is the first item out: LIFO, Last In, First Out. Everything else follows from that one rule.

  • LIFO order

    The newest item always leaves first.

  • One access point

    Only the top can be read or removed. Items below are out of reach.

  • Reverse on the way out

    Push 1, 2, 3 and you pop 3, 2, 1. That is why stacks reverse things.

The picture

LIFO in one picture

A chef adds a plate to the top of a tall pile of plates on a kitchen counter while a waiter lifts a plate off the same top.
A pile of plates: new plates go on top, and the next plate taken is the one on top.
The whole life of a stack
  1. 1PushAdd an item on top
  2. 2PeekRead the top, change nothing
  3. 3PopRemove the top, newest first

Every stack operation touches the top and nothing else.

The API

Core operations

OperationWhat it doesOn 10, 20, 30, 40
push(x)Puts x on toppush(50) gives 10, 20, 30, 40, 50
pop()Removes and returns the topreturns 40, leaves 10, 20, 30
peek()Returns the top without removing itreturns 40, stack unchanged
is_empty()True when there is nothing to popFalse
size()Number of items4
The stack is drawn bottom to top: 10 is the base, 40 is the top at index 3.

Searching for a value is not a stack operation. If you find yourself needing it often, a stack is the wrong tool.

Under the hood

How push and pop work

push(x)

Only a fixed-size stack can be full. A dynamic array grows instead.

pop()

peek() follows the same path but stops after reading the value.

Complexity

What each operation costs

OperationTimeSpaceWhy
pushO(1)O(1) amortisedO(1)O(1)Writes one slot at the top; a dynamic array sometimes doubles
popO(1)O(1)O(1)O(1)Removes one slot at the top
peekO(1)O(1)O(1)O(1)Reads the top directly
is_empty, sizeO(1)O(1)O(1)O(1)The size is tracked as items come and go
searchO(n)O(n)O(1)O(1)Has to walk down the whole stack
the stack itselfO(n)O(n)One slot per stored item

Why push stays O(1) on a dynamic array

1+2+4+⋯+n⏟copies made by all resizes  <  2n⇒2nn=O(1) per push\underbrace{1 + 2 + 4 + \dots + n}_{\text{copies made by all resizes}} \;<\; 2n \quad\Rightarrow\quad \frac{2n}{n} = O(1) \text{ per push}
When the array is full it doubles and copies everything. Copies happen at sizes 1, 2, 4 and so on, so nn pushes cause fewer than 2n2n copies in total. One push can be slow; the average is constant.

Comparison

Stack vs queue vs array

StackQueueArray
OrderLIFOFIFOAny index
InsertO(1)O(1) at the topO(1)O(1) at the backO(1)O(1) at the end, O(n)O(n) in the middle
RemoveO(1)O(1) at the topO(1)O(1) at the frontO(1)O(1) at the end, O(n)O(n) in the middle
FindO(n)O(n)O(n)O(n)O(1)O(1) by index, O(n)O(n) by value
Typical useUndo, DFS, parsingBFS, schedulingRandom access

Use a stack when

  • The most recent item must be handled first.
  • Things nest: brackets, tags, function calls.
  • You do DFS or backtracking, or turn recursion into a loop.
  • You build undo and redo, or back and forward.

Do not use a stack when

  • You need random access by index (use an array).
  • You need first-in, first-out order or BFS (use a queue).
  • You need access at both ends (use a deque).
  • You search for values often (use a set or dict).

Implementation

Three ways to build one

  • Dynamic array

    Top is the end of the list: append(x) and pop(). The usual choice in Python.

  • Linked list

    Top is the head: head = Node(x, head). Never resizes, costs one pointer per node.

  • Fixed-size array

    A preallocated array plus a top index. Must check for full before every push.

Python
stack = []stack.append(10)       # pushstack.append(20)stack.append(30)print(stack[-1])       # peek -> 30print(stack.pop())     # pop  -> 30print(len(stack) == 0) # is_empty -> False
A Python list is already a stack. Use the end, not the front.
Edit and run it in your browser
Python
class Node:    def __init__(self, val, next=None):        self.val = val        self.next = nextclass LinkedStack:    def __init__(self):        self.head = None        self.count = 0    def push(self, val):        self.head = Node(val, self.head)   # new node becomes the top        self.count += 1    def pop(self):        if self.head is None:            raise IndexError("pop from empty stack")        val = self.head.val        self.head = self.head.next        self.count -= 1        return vals = LinkedStack()s.push(1)s.push(2)print(s.pop(), s.pop())   # 2 1
A linked-list stack: the head of the list is the top.
Edit and run it in your browser

In the wild

Where stacks run

  • Function calls

    Each call pushes a frame with its arguments, locals and return address. Each return pops it.

  • Undo and redo

    Editors push every action. Undo pops it onto a redo stack.

  • Browser history

    Back and Forward are two stacks that trade pages.

  • Parsing

    Compilers check brackets and evaluate expressions with operator precedence.

  • DFS and backtracking

    Push a choice, explore, pop to go back. Mazes, N-Queens, tree walks.

  • Next greater element

    A monotonic stack answers it in one pass, O(n)O(n).

Browser back and forward with two stacks

Undo and redo in an editor use exactly the same two-stack trick.

Deep dive

The call stack up close

When main() calls calculate(), which calls multiply(), three frames pile up. Each function waits for the one above it. Returns happen in reverse, newest first.

Calls push frames, returns pop them

The deepest call finishes first. A stack trace is this stack printed top to bottom.

Errors

Overflow and underflow

Python
class SafeStack:    def __init__(self, max_size=1000):        self.items = []        self.max_size = max_size    def push(self, item):        if len(self.items) >= self.max_size:            raise OverflowError("stack overflow: stack is full")        self.items.append(item)    def pop(self):        if not self.items:            raise IndexError("stack underflow: stack is empty")        return self.items.pop()s = SafeStack(max_size=2)s.push("a")s.push("b")print(len(s.items) >= s.max_size)   # True: one more push overflows
Guard both ends: check full before push, empty before pop.
Edit and run it in your browser

Preventing overflow

  • Give every recursion a reachable base case.
  • Check capacity before pushing onto a fixed-size stack.
  • Turn very deep recursion into a loop with an explicit stack.

Preventing underflow

  • Check is_empty() before every pop() or peek().
  • Treat empty input as its own case.
  • Validate that input is balanced, for example brackets.

Pattern spotting

Spotting a stack problem

Should I use a stack?

  • Matching brackets

    Push openers; on a closer, pop and check it matches.

  • Monotonic stack

    Keep values sorted; pop whatever breaks the order. Daily temperatures, next greater.

  • Expression evaluation

    One stack for operands, one for operators, or a single stack for postfix.

  • Backtracking

    Push a state before exploring it, pop to go back.

Matching brackets, one character at a time

The last check catches leftover openers such as ((.

Recap

Key takeaways

Key points

  • A stack is LIFO: the last item pushed is the first popped.
  • push, pop, peek, is_empty and size are O(1)O(1); search is O(n)O(n); space is O(n)O(n).
  • In Python, use a list and keep the top at the end: append and pop().
  • The call stack, undo, browser history and parsing all run on stacks.
  • Overflow is pushing past capacity or recursing without a base case; underflow is popping from empty.
  • Signals: newest first, nesting, matching, DFS, next greater element.

Sources