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.