M08 · Stacks

Stacks: Last In, First Out on the End of an Array

A stack only lets you touch the element added most recently. That restriction is what makes it useful: undo histories, function calls and bracket matching all follow it. Built on the end of a dynamic array, every operation is constant time on average and nothing ever shifts.

~30 minBeginnerC# · Python · Java · C++
Curriculum: M08 Stacks · 1 of 1 lessons available

You will be able to

  • Describe LIFO order and predict the output of any sequence of push, pop and peek.
  • Explain why the end of a dynamic array, not the front, is the top of the stack, and derive the costs of each operation.
  • Handle underflow explicitly and say how each language reports it.
  • Use a stack to check balanced brackets and to evaluate a postfix expression.
  • Pick the idiomatic stack in C#, Python, Java and C++, and avoid the legacy or surprising ones.

Helpful before this lesson

  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.
  • M07 Linked Lists — Nodes and pointers: what O(1) insertion really requires, and the classic pointer techniques.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

Think of a pile of plates. You put a plate on top and you take the top plate off; reaching into the middle is not part of the deal. A stack is a collection with exactly that rule: last in, first out (LIFO). It has three operations:

  • push(x): put x on top.
  • pop(): remove the top element and return it.
  • peek() (also called top): return the top element without removing it.

That is all. No search, no index access, no insertion in the middle. The restriction is the point: whenever a problem has the shape "the most recent unfinished thing must be finished first", a stack models it directly. Your program's call stack works this way: the function called last returns first. So do undo histories, browser back buttons, and the depth-first search you will meet later.

Where is the top?

The lab draws a vertical column of slots: a dynamic array standing on its end. Index 0 is the bottom; the top is the last used index, size - 1.

Why the end and not the front? Because of what each costs in an array:

  • Adding or removing at the end writes or clears one slot. Nothing moves.
  • Adding or removing at the front shifts every other element by one. That is O(n).

So the teaching implementation is a thin wrapper around the language's dynamic array:

push(x):  items.append(x)
pop():    if items is empty: fail with underflow
          return items.remove_last()
peek():   if items is empty: fail with underflow
          return items[last]

Run the Last in, first out preset: 1, 2 and 3 go in, and three pops return 3, 2, 1. The newest element always sits at the highest index.

Costs

Operation Time Why
push amortized O(1); O(n) on the push that resizes Appending to a dynamic array (see the dynamic arrays lesson).
pop O(1) Removing the last element shifts nothing.
peek O(1) One read at a known index.
size, isEmpty O(1) Stored count.
space O(n) Plus spare capacity left over from growth.

The O(n) push happens only when the underlying buffer is full. Because buffers grow geometrically, n pushes cost O(n) in total. If you need a strict O(1) bound on every push (rare outside real-time systems), a stack built from linked nodes gives it, at the cost of one allocation and one extra reference per element. Most standard libraries choose the array.

Underflow and overflow

Popping or peeking an empty stack is underflow, and there is no sensible value to return. The teaching implementation checks first and fails loudly. Run the Underflow preset: the first pop is rejected, and the stack keeps working normally afterwards.

Language Teaching version Built-in behaviour on empty
C# InvalidOperationException Stack<T>.Pop()/Peek() throw InvalidOperationException; TryPop/TryPeek return false
Python IndexError list.pop() raises IndexError; items[-1] raises IndexError
Java NoSuchElementException ArrayDeque.pop() throws NoSuchElementException, but peek() returns null
C++ std::underflow_error std::stack::top() and pop() on an empty stack are undefined behaviour

Overflow means pushing onto a full stack. A stack on a dynamic array grows instead, so it only overflows when memory runs out. Fixed-size stacks do overflow: the call stack is one, which is why unbounded recursion ends in a StackOverflowError (Java), a process crash in .NET, RecursionError in Python (CPython enforces a depth limit), or undefined behaviour in C++.

Invariants

  • size equals the number of pushes minus the number of successful pops.
  • The element at index size - 1 is the one pushed most recently among those not yet popped.
  • The order of the remaining elements, bottom to top, never changes: a stack never reorders.

Using a stack: matching brackets

Is {[()()]} balanced? Is ([)]? Scan left to right. Push every opening bracket. On a closing bracket, the top of the stack must be its partner; pop it. At the end the stack must be empty.

for ch in text:
    if ch in "([{": push(ch)
    elif ch in ")]}":
        if stack is empty or pop() != partner(ch): return false
return stack is empty

The stack works because brackets nest: the most recently opened one must close first, which is LIFO. The scan is O(n) time and O(n) space in the worst case (all openers). Three failure modes: a closer with an empty stack, a closer that does not match the top, and openers left over at the end.

Using a stack: postfix evaluation

In postfix notation (reverse Polish), the operator follows its operands: 3 4 + 2 * means (3 + 4) * 2. Push numbers; on an operator, pop two values, apply it, push the result.

3       → [3]
4       → [3, 4]
+       → pop 4, pop 3, push 7      → [7]
2       → [7, 2]
*       → pop 2, pop 7, push 14     → [14]

The first value popped is the right operand. For - and / that order matters: 8 2 - is 6, not -6.

Built-in stacks

C# Python Java C++
Type Stack<T> list ArrayDeque<E> via Deque std::stack<T> (adaptor)
Push Push(x) append(x) push(x) push(x) / emplace(...)
Pop Pop() returns the top pop() returns the top pop() returns the top pop() returns void
Peek Peek() items[-1] peek() top()
Iteration order top to bottom bottom to top top to bottom not iterable

Details that matter:

  • C# Stack<T> is array-backed. Push is O(1) unless the array must grow, then O(n), as its docs state. Enumerating it, or calling ToArray(), yields the top element first.
  • Python has no stack class; the tutorial recommends a list with append and pop(). Do not use pop(0) or insert(0, x): those work at the front and are O(n). collections.deque also works as a stack, and queue.LifoQueue exists for passing items between threads.
  • Java has a Stack class, but it is a legacy type that extends Vector, so its methods are synchronized and it exposes index-based Vector methods that break the stack abstraction. Its own Javadoc recommends the Deque interface instead: Deque<Integer> stack = new ArrayDeque<>();. ArrayDeque rejects null elements, and peek() returns null on an empty deque rather than throwing, so check isEmpty() when the difference matters.
  • C++ std::stack is an adaptor over another container, std::deque by default; std::vector and std::list also work (std::stack<int, std::vector<int>>). pop() returns nothing: read top() first, then pop(). The split exists so that removing an element never depends on copying it out, which could throw and lose the element. The teaching C++ version moves the top out before pop_back() to return it in one call.

The teaching implementation

The four listings wrap List<T>, list, ArrayList and std::vector, each pushing and popping at the end, with an explicit empty check before pop and peek. They are checked against one shared fixture of push, pop and peek sequences, including underflow on an empty stack. In real code, use the built-in type from the table above; the wrapper exists to show that a stack is a discipline on top of a dynamic array, not a new kind of memory.

Common mistakes

  • Using the front of an array as the top. Each push and pop becomes O(n).
  • Popping without checking for empty, or, in C++, calling top() on an empty std::stack.
  • Treating Java's peek() result as non-null on an ArrayDeque that might be empty.
  • Swapping operands when evaluating postfix: the first pop is the right-hand side.
  • Expecting C#'s Stack<T> and Java's legacy Stack to iterate in the same order. The C# stack and ArrayDeque go top first; Java's Stack, being a Vector, goes bottom first.

Edge cases

  • Empty stack: pop and peek underflow; a later push works normally.
  • One element: it is both the top and the bottom; one pop empties the stack.
  • Push after pop: the freed slot is reused, so the array does not grow again until it is full.
  • Many pushes: an occasional push triggers a resize of the underlying array.

Worked practice

1. Starting empty: push 4, push 7, pop, push 1, peek, pop, pop. What do the pop and peek calls return?

Answer

pop → 7, peek → 1, pop → 1, pop → 4. The stack ends empty.

2. Trace the bracket checker on ([)]. Where does it fail?

Answer

Push (, push [. The next character is ), but the top is [, which does not match, so it returns false at index 2. Counting brackets alone would wrongly accept this string; the stack checks nesting.

3. Evaluate the postfix expression 5 1 2 + 4 * + 3 -.

Answer

1 2 + → 3; 3 4 * → 12; 5 12 + → 17; 17 3 - → 14.

4. For each element of [2, 1, 5, 3], find the next element to its right that is larger (or -1). How can a stack do it in one pass?

Answer

Answer: [5, 5, -1, -1]. Scan left to right keeping a stack of indices still waiting for an answer. For each new value, pop every waiting index whose value is smaller and record the new value as its answer, then push the new index. The stack's values always decrease from bottom to top, which is why it is called a monotonic stack. Each index is pushed and popped at most once: O(n).

Summary

  • A stack is LIFO: push, pop and peek, all at the top.
  • On a dynamic array the top is the end, so push is amortized O(1) and pop and peek are O(1).
  • Underflow must be handled; each language reports it differently, and C++'s std::stack does not check.
  • Nested structure (brackets, calls, postfix expressions) is where stacks shine.
  • Use Stack<T>, a Python list, ArrayDeque through Deque, or std::stack; avoid Java's legacy Stack.

Full implementation

The array-backed stack in four languages, checked against one shared fixture of push, pop and peek sequences, including underflow on an empty stack.

namespace Bekadan.Dsa.Examples.StacksQueues;
 
/// <summary>A LIFO stack on the end of a dynamic array: push and pop are amortized O(1).</summary>
public sealed class ArrayStack<T>
{
    private readonly List<T> _items = [];
 
    public int Count => _items.Count;
 
    public IReadOnlyList<T> BottomToTop => _items;
 
    public void Push(T item)
    {
        _items.Add(item); // the end of the array is the top
    }
 
    public T Pop()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("The stack is empty.");
        T top = _items[^1];
        _items.RemoveAt(_items.Count - 1); // removing the last element shifts nothing
        return top;
    }
 
    public T Peek()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("The stack is empty.");
        return _items[^1];
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/StacksQueues/ArrayStack.cs

"""An array-backed LIFO stack."""
 
from typing import Generic, TypeVar
 
T = TypeVar("T")
 
 
class ArrayStack(Generic[T]):
    """LIFO on the end of a list: push and pop are amortized O(1)."""
 
    def __init__(self) -> None:
        self._items: list[T] = []
 
    def __len__(self) -> int:
        return len(self._items)
 
    def bottom_to_top(self) -> list[T]:
        return list(self._items)
 
    def push(self, item: T) -> None:
        self._items.append(item)  # the end of the list is the top
 
    def pop(self) -> T:
        if not self._items:
            raise IndexError("pop from an empty stack")
        return self._items.pop()  # removing the last element shifts nothing
 
    def peek(self) -> T:
        if not self._items:
            raise IndexError("peek at an empty stack")
        return self._items[-1]

Tested on CPython 3.14.0 · examples/python/dsa_examples/array_stack.py

package dev.bekadan.dsa.stacks;
 
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
 
/** A LIFO stack on the end of an ArrayList: push and pop are amortized O(1). */
public final class ArrayStack<T> {
    private final List<T> items = new ArrayList<>();
 
    public int size() {
        return items.size();
    }
 
    public List<T> bottomToTop() {
        return List.copyOf(items);
    }
 
    public void push(T item) {
        items.add(item); // the end of the list is the top
    }
 
    public T pop() {
        if (items.isEmpty()) {
            throw new NoSuchElementException("The stack is empty.");
        }
        return items.remove(items.size() - 1); // removing the last element shifts nothing
    }
 
    public T peek() {
        if (items.isEmpty()) {
            throw new NoSuchElementException("The stack is empty.");
        }
        return items.get(items.size() - 1);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/stacks/ArrayStack.java

#pragma once
 
#include <stdexcept>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// A LIFO stack on the end of a std::vector: push and pop are amortized O(1).
// (std::stack is the standard adapter for this; this class shows the mechanism.)
template <typename T>
class ArrayStack {
public:
    [[nodiscard]] std::size_t size() const noexcept { return items_.size(); }
    [[nodiscard]] const std::vector<T>& bottom_to_top() const noexcept { return items_; }
 
    void push(T item) {
        items_.push_back(std::move(item));  // the end of the vector is the top
    }
 
    T pop() {
        if (items_.empty())
            throw std::underflow_error("pop from an empty stack");
        T top = std::move(items_.back());
        items_.pop_back();  // removing the last element shifts nothing
        return top;
    }
 
    [[nodiscard]] const T& peek() const {
        if (items_.empty())
            throw std::underflow_error("peek at an empty stack");
        return items_.back();
    }
 
private:
    std::vector<T> items_;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/array_stack.hpp

References