M03 · Big O

Best, Worst, Average, Expected and Amortized Cost

A complexity claim is incomplete until it says which inputs it covers. Linear search is Θ(1) on a lucky input and Θ(n) on an unlucky one. A dynamic array append is usually one write and occasionally a full copy. This lesson separates best, worst and average case, expected cost, and amortized cost, and shows why amortized is a guarantee while average is not.

~35 minBeginnerC# · Python · Java · C++
Curriculum: M03 Big O · 3 of 3 lessons available

You will be able to

  • State best-, worst- and average-case costs of an algorithm, and the input distribution an average assumes.
  • Tell average case (over inputs) from expected cost (over the algorithm's own random choices).
  • Prove an amortized bound with the aggregate method and the accounting (banker's) method.
  • Explain why amortized O(1) is a worst-case guarantee for sequences, and when a single slow operation still matters.
  • Read the complexity wording of C#, Python, Java and C++ documentation correctly.

Helpful before this lesson

  • M01 Algorithmic Thinking — Turn a vague task into precise inputs, outputs and constraints, then argue that a solution is correct.

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.

The question behind every bound

"Linear search is O(n)" leaves out which inputs we are talking about. For a fixed size n there are many inputs, and the algorithm may do very different amounts of work on them. Each of the following is a separate function of n, and each can be stated with O, Θ or Ω:

Measure Over what Linear search, n elements
Best case the cheapest input of size n target first: 1 comparison, Θ(1)
Worst case the most expensive input of size n target absent: n comparisons, Θ(n)
Average case inputs drawn from a stated distribution target present, uniformly random position: (n + 1)/2, Θ(n)
Expected the algorithm's own random choices, for any fixed input (not randomized)
Amortized the total of any sequence of operations, divided by its length (single operation)

The linear search that stops early exercise walks through the first three rows. In the linear search playground, the Best case and Not found presets are the two extremes.

Best and worst case

Worst case is the default in algorithm analysis because it is a guarantee: no input of size n costs more. Best case is rarely useful on its own: almost any algorithm can be made fast on some special input. It does tell you about adaptive algorithms, whose cost depends on how "nice" the input is. Insertion sort is Θ(n) on sorted input and Θ(n²) on reversed input; that is why it is used on nearly sorted data.

"The best case is Θ(1)" is not the same as "the algorithm is Ω(1)". Every algorithm is Ω(1). Name the case, then the bound.

Average case needs a distribution

An average is only meaningful together with the distribution it averages over. Linear search averages (n + 1)/2 comparisons if the target is present and equally likely to be at each position. If the target is usually absent, the average approaches n. If it is usually near the front, it may be close to 1.

Quicksort is the classic example. With a fixed pivot rule, the average over all orderings of distinct values is Θ(n log n) comparisons, but specific inputs (for a first-element pivot: sorted input) cost Θ(n²). Real data is not uniformly random, so "average Θ(n log n)" alone promises little for your data. See the quicksort lesson.

Expected cost: randomness inside the algorithm

If the algorithm makes random choices, you can analyse the expected cost for each fixed input, averaging over the algorithm's coins instead of over inputs. Quicksort with a uniformly random pivot takes expected Θ(n log n) comparisons on every input: no input is bad, only some coin flips are unlucky, and very unlucky runs are very unlikely.

Hash tables are usually described the same way: a lookup is expected O(1) under the assumption that the hash function spreads keys evenly, with a Θ(n) worst case when many keys collide. The hash table lesson shows what a collision chain costs.

Amortized cost: a guarantee for sequences

Some operations are cheap almost every time and expensive occasionally, in a pattern the data structure controls. Amortized analysis bounds the total cost of any sequence of m operations and divides by m.

The lab above is the standard example. A dynamic array that doubles its capacity when full:

  • an append with spare room writes one element;
  • an append into a full buffer allocates a buffer twice as large and copies all n elements first.

Run Doubling from empty and watch the Resize copies metric jump at sizes 1, 2, 4 and 8 while the average writes per append stays below 3.

Aggregate method. Add up the actual costs of n appends from empty. There are n writes of new elements. Resizes copy 1 + 2 + 4 + … + 2ᵏ elements, with 2ᵏ < n, which is less than 2n. Total: fewer than 3n writes for any n appends, so the amortized cost is less than 3 = O(1) per append. The amortized appends exercise measures this count and checks it.

Accounting (banker's) method. Charge every append 3 units. One pays for writing the element; two go into a "bank" stored with it. When the buffer of capacity c fills, the c/2 elements added since the last resize have saved c units in total, exactly enough to copy all c elements. The bank never goes negative, so the charge of 3 per append covers every real cost.

Potential method (for reference): define a potential Φ, such as Φ = 2 · size − capacity, and show that actual cost + change in Φ is bounded by a constant for each operation. The accounting method is the same idea with the potential stored as credits.

Growing by a constant number of slots instead breaks all three arguments: n appends then copy about n²/(2k) elements, Θ(n²) total. The dynamic arrays lesson derives both.

Amortized is not average

Average case Amortized
Averages over possible inputs (needs a distribution) the operations of one sequence
Holds for every input? no; an unlucky input can be worse yes; every sequence of m operations
Probability involved? yes no
A single operation can be slow? yes yes

The last row is the practical caveat. An amortized O(1) append is still Θ(n) for the one append that resizes. Code with a latency limit per operation (an audio callback, a frame of a game, a trading system) may care about that single step; pre-sizing (EnsureCapacity, reserve, ensureCapacity) removes it.

Other amortized bounds in this lab: the sliding window inner loop (the left pointer moves at most n times in total), the two-pointer sweep, and union-find with path compression in the disjoint sets lesson.

Reading the documentation

Libraries use these words carefully, and the differences are real:

Language Operation Documented cost
C# List<T>.Add O(1) if Count is less than Capacity; O(n) when the capacity must grow. The docs state both cases rather than an amortized bound, but with the doubling growth the amortized cost is O(1).
C# Dictionary<TKey,TValue> lookup "approaches an O(1) operation" (it depends on hash quality)
Python list.append O(1) amortized worst case (CPython, per the TimeComplexity page)
Python x in set, dict[key] O(1) average, O(n) worst case
Java ArrayList.add "runs in amortized constant time"
Java HashMap.get / put "constant-time performance … assuming the hash function disperses the elements properly"
C++ std::vector::push_back amortized constant
C++ std::unordered_map::find constant on average, worst case linear in the size
C++ std::sort O(n log n) comparisons; since C++11 this is required in the worst case, which rules out plain quicksort

Common mistakes

  • Stating a bound without a case. "O(1)" for a hash lookup is expected or average, not worst case.
  • Calling amortized "average". Amortized needs no randomness and holds for every sequence.
  • Multiplying the worst single operation by n. n appends are not Θ(n²) just because one append can be Θ(n); sum the actual costs.
  • Averaging over a distribution nobody checked. "Average Θ(n log n)" quicksort with a fixed pivot can still be Θ(n²) on your data.
  • Forgetting latency. An amortized bound says nothing about the worst single operation.

Worked practice

1. Insertion sort on n values: best, worst and average comparisons?

Best (sorted): n − 1, Θ(n). Worst (reversed): n(n − 1)/2, Θ(n²). Average over random orderings of distinct values: about n²/4, still Θ(n²), because each pair is inverted with probability 1/2 and each inversion costs one shift.

2. A binary counter of k bits is incremented n times from 0. One increment can flip k bits. What is the amortized cost per increment?

Bit 0 flips every time, bit 1 every second time, bit 2 every fourth time, and so on. Total flips ≤ n + n/2 + n/4 + … < 2n. So the amortized cost is O(1) per increment, though one increment (from 0111…1 to 1000…0) flips every bit.

3. A queue is built from two stacks: push onto in; to pop, if out is empty, move everything from in to out, then pop out. Amortized cost?

Each element is pushed onto in once, moved to out at most once, and popped from out once: at most 3 stack operations per element over its lifetime. Any sequence of m operations costs O(m), so O(1) amortized per operation. A single pop can still move n elements.

4. Is "quicksort with a random pivot is O(n log n) on average" the right wording?

More precisely: its expected number of comparisons is Θ(n log n) on every input, where the expectation is over the random pivots. "Average" suggests averaging over inputs, which is a weaker statement.

Summary

  • Best, worst and average case are different functions of n; name the case before the bound.
  • Average case needs an input distribution; expected cost averages over the algorithm's own random choices and holds for every input.
  • Amortized cost bounds the total of any sequence: no probability, a real guarantee.
  • Doubling a dynamic array's capacity makes n appends cost fewer than 3n writes: amortized O(1), though one append is Θ(n).
  • Documentation uses these words precisely: "amortized constant", "average", "assuming a good hash" each mean something different.

Full implementation

The same class in four languages, each checked against one shared set of test cases (append with and without a resize, front, middle and end inserts, removals, out-of-range indices, duplicates, extreme values) and a randomized comparison with the language's own dynamic array.

namespace Bekadan.Dsa.Examples.DynamicArrays;
 
/// <summary>
/// A growable array backed by a fixed-size buffer that doubles when full.
/// A teaching model of <see cref="List{T}"/>, which uses Array.Copy and starts
/// at capacity 4, but has the same costs.
/// </summary>
public sealed class DynamicArray<T>
{
    private T[] _items;
    private int _count;
 
    public DynamicArray(int initialCapacity = 0)
    {
        ArgumentOutOfRangeException.ThrowIfNegative(initialCapacity);
        _items = new T[initialCapacity];
    }
 
    public int Count => _count;
 
    public int Capacity => _items.Length;
 
    public T this[int index]
    {
        get
        {
            if (index < 0 || index >= _count)
                throw new ArgumentOutOfRangeException(nameof(index));
            return _items[index];
        }
        set
        {
            if (index < 0 || index >= _count)
                throw new ArgumentOutOfRangeException(nameof(index));
            _items[index] = value;
        }
    }
 
    public void Add(T item)
    {
        if (_count == _items.Length)
            Grow();
        _items[_count] = item;
        _count++;
    }
 
    public void Insert(int index, T item)
    {
        if (index < 0 || index > _count)
            throw new ArgumentOutOfRangeException(nameof(index));
        if (_count == _items.Length)
            Grow();
        for (int i = _count; i > index; i--)
            _items[i] = _items[i - 1];
        _items[index] = item;
        _count++;
    }
 
    public T RemoveAt(int index)
    {
        if (index < 0 || index >= _count)
            throw new ArgumentOutOfRangeException(nameof(index));
        T removed = _items[index];
        for (int i = index; i < _count - 1; i++)
            _items[i] = _items[i + 1];
        _items[_count - 1] = default!; // drop the leftover reference for the GC
        _count--;
        return removed;
    }
 
    private void Grow()
    {
        int newCapacity = _items.Length == 0 ? 1 : _items.Length * 2;
        var newItems = new T[newCapacity];
        for (int i = 0; i < _count; i++)
            newItems[i] = _items[i];
        _items = newItems; // the old array becomes garbage
    }
}

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

"""A growable array backed by a fixed-size buffer that doubles when full.
 
Python's own list is already a dynamic array (CPython over-allocates by about
1/8). This class models one with an explicit buffer so each resize, copy and
shift is visible. Negative indices are not supported, unlike list.
"""
 
 
class DynamicArray[T]:
    def __init__(self, initial_capacity: int = 0) -> None:
        if initial_capacity < 0:
            raise ValueError("initial_capacity must not be negative")
        self._items: list[T | None] = [None] * initial_capacity
        self._count = 0
 
    def __len__(self) -> int:
        return self._count
 
    @property
    def capacity(self) -> int:
        return len(self._items)
 
    def __getitem__(self, index: int) -> T:
        if not 0 <= index < self._count:
            raise IndexError("index out of range")
        return self._items[index]  # type: ignore[return-value]
 
    def __setitem__(self, index: int, value: T) -> None:
        if not 0 <= index < self._count:
            raise IndexError("index out of range")
        self._items[index] = value
 
    def append(self, value: T) -> None:
        if self._count == len(self._items):
            self._grow()
        self._items[self._count] = value
        self._count += 1
 
    def insert(self, index: int, value: T) -> None:
        if not 0 <= index <= self._count:
            raise IndexError("index out of range")
        if self._count == len(self._items):
            self._grow()
        for i in range(self._count, index, -1):
            self._items[i] = self._items[i - 1]
        self._items[index] = value
        self._count += 1
 
    def remove_at(self, index: int) -> T:
        if not 0 <= index < self._count:
            raise IndexError("index out of range")
        removed = self._items[index]
        for i in range(index, self._count - 1):
            self._items[i] = self._items[i + 1]
        self._items[self._count - 1] = None  # drop the leftover reference
        self._count -= 1
        return removed  # type: ignore[return-value]
 
    def _grow(self) -> None:
        new_capacity = 1 if not self._items else len(self._items) * 2
        new_items: list[T | None] = [None] * new_capacity
        for i in range(self._count):
            new_items[i] = self._items[i]
        self._items = new_items  # the old list loses its last reference

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

package dev.bekadan.dsa.arrays;
 
/**
 * A growable array backed by a fixed-size buffer that doubles when full.
 * A teaching model of what ArrayList does; OpenJDK's ArrayList grows by
 * about 1.5x and uses System.arraycopy, but the costs are the same.
 */
public final class DynamicArray<E> {
    private Object[] items;
    private int size;
 
    public DynamicArray(int initialCapacity) {
        if (initialCapacity < 0) {
            throw new IllegalArgumentException("initialCapacity must not be negative");
        }
        items = new Object[initialCapacity];
    }
 
    public DynamicArray() {
        this(0);
    }
 
    public int size() {
        return size;
    }
 
    public int capacity() {
        return items.length;
    }
 
    @SuppressWarnings("unchecked")
    public E get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size);
        }
        return (E) items[index];
    }
 
    public void set(int index, E element) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size);
        }
        items[index] = element;
    }
 
    public void add(E element) {
        if (size == items.length) {
            grow();
        }
        items[size] = element;
        size++;
    }
 
    public void add(int index, E element) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size);
        }
        if (size == items.length) {
            grow();
        }
        for (int i = size; i > index; i--) {
            items[i] = items[i - 1];
        }
        items[index] = element;
        size++;
    }
 
    @SuppressWarnings("unchecked")
    public E remove(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size);
        }
        E removed = (E) items[index];
        for (int i = index; i < size - 1; i++) {
            items[i] = items[i + 1];
        }
        items[size - 1] = null; // drop the leftover reference for the GC
        size--;
        return removed;
    }
 
    private void grow() {
        int newCapacity = items.length == 0 ? 1 : items.length * 2;
        Object[] newItems = new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newItems[i] = items[i];
        }
        items = newItems; // the old array becomes garbage
    }
}

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

#pragma once
 
#include <cstddef>
#include <memory>
#include <stdexcept>
#include <utility>
 
namespace bekadan::dsa {
 
// A growable array backed by a fixed-size buffer that doubles when full.
// A teaching model of std::vector. Simplification: the buffer is created with
// make_unique<T[]>, which default-constructs every slot, so T must be default
// constructible; std::vector instead constructs elements in raw storage.
template <typename T>
class DynamicArray {
public:
    explicit DynamicArray(std::size_t initial_capacity = 0)
        : data_(std::make_unique<T[]>(initial_capacity)), capacity_(initial_capacity) {}
 
    [[nodiscard]] std::size_t size() const noexcept { return size_; }
    [[nodiscard]] std::size_t capacity() const noexcept { return capacity_; }
 
    [[nodiscard]] const T& at(std::size_t index) const {
        if (index >= size_) {
            throw std::out_of_range("DynamicArray::at: index out of range");
        }
        return data_[index];
    }
 
    void set(std::size_t index, T value) {
        if (index >= size_) {
            throw std::out_of_range("DynamicArray::set: index out of range");
        }
        data_[index] = std::move(value);
    }
 
    void push_back(T value) {
        if (size_ == capacity_) {
            grow();
        }
        data_[size_] = std::move(value);
        ++size_;
    }
 
    void insert(std::size_t index, T value) {
        if (index > size_) {
            throw std::out_of_range("DynamicArray::insert: index out of range");
        }
        if (size_ == capacity_) {
            grow();
        }
        for (std::size_t i = size_; i > index; --i) {
            data_[i] = std::move(data_[i - 1]);
        }
        data_[index] = std::move(value);
        ++size_;
    }
 
    T remove_at(std::size_t index) {
        if (index >= size_) {
            throw std::out_of_range("DynamicArray::remove_at: index out of range");
        }
        T removed = std::move(data_[index]);
        for (std::size_t i = index; i + 1 < size_; ++i) {
            data_[i] = std::move(data_[i + 1]);
        }
        data_[size_ - 1] = T{};  // release whatever the vacated slot still owns
        --size_;
        return removed;
    }
 
private:
    void grow() {
        const std::size_t new_capacity = capacity_ == 0 ? 1 : capacity_ * 2;
        auto new_data = std::make_unique<T[]>(new_capacity);
        for (std::size_t i = 0; i < size_; ++i) {
            new_data[i] = std::move(data_[i]);
        }
        data_ = std::move(new_data);  // frees the old buffer immediately
        capacity_ = new_capacity;
    }
 
    std::unique_ptr<T[]> data_;
    std::size_t capacity_ = 0;
    std::size_t size_ = 0;
};
 
}  // namespace bekadan::dsa

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

References