Sub topic 1
Three ways to talk about cost: worst case, average case, amortised
Prerequisites
This chapter assumes you already have the following:
- Big-O notation and basic asymptotic reasoning. You can say why a loop over n items is O(n).
- Arrays and indexing. You know a fixed-size array is allocated with a set capacity, and that this capacity cannot change in place.
- A basic idea of a hash function and a hash table.
- Enough Python to read short programs.
The chapter introduces no proofs yet. It sets up the vocabulary that the rest of the tutorial uses: worst-case, average-case (expected) and amortised cost. Later chapters prove the bounds for dynamic arrays and hash tables.
Why one number is not enough
"This operation is O(1)" can mean three different things. Take appending to a list in Python. Most appends write one value and finish. Occasionally an append has to allocate a bigger block of memory and copy every existing element. Both facts are true, and a single cost figure cannot describe both.
Each of the three cost models answers a different question:
- Worst case: how bad can one operation be?
- Average case: how costly is an operation on typical input, under some assumption about what typical means?
- Amortised: how costly is each operation when I look at a whole sequence of operations and guarantee the total?
Worst-case cost
The worst-case cost of an operation is the largest cost it can incur on any input of a given size. It is a guarantee about each individual call. If a function is O(n) in the worst case, no call ever does more than a constant times n work.
Worst-case bounds need no assumptions. They are also the right tool when a single slow call causes harm, such as a missed deadline in a real-time system. The weakness is pessimism. If the bad case is rare, the worst-case bound describes a cost you almost never pay.
For a dynamic array that holds n elements and is full, one append costs about n steps: it copies all n elements to a new array. So the worst-case cost of a single append is O(n). That statement is correct, but it hides the fact that this expensive append is rare.
Average-case cost
The average-case cost is the expected cost when the input is drawn from a probability distribution. The result depends on that distribution. You must state it, and the bound holds only if reality matches it.
The following program searches for a target in an unsorted list. It picks the target uniformly at random, so each position is equally likely.
import random
def comparisons(items, target):
"""Number of elements examined by a linear search."""
count = 0
for x in items:
count += 1
if x == target:
break
return count
n = 1000
items = list(range(n))
random.seed(1)
samples = [comparisons(items, random.randrange(n)) for _ in range(10000)]
print("worst observed:", max(samples))
print("average:", sum(samples) / len(samples))The average comes out near n/2, which is 500. The worst observed value is at or near 1000. Both are Θ(n), so Big-O does not distinguish them here. The constant factor does.
Now suppose a user always searches for the last item. Every search costs n comparisons. The average-case figure of n/2 was only valid under the uniform assumption. This is the central risk of average-case analysis: the input distribution is an assumption, and an adversary or a quirk of your workload can violate it.
A related notion is expected cost over an algorithm's own random choices. Randomised quicksort with a random pivot runs in O(n log n) expected time on every input. The probability comes from the coin flips the algorithm makes, not from the data. The bound therefore holds even for adversarial input. Keep this distinction in mind. Chapter 10 returns to it when hash tables enter the picture.
Amortised cost
Amortised analysis looks at a sequence of operations and bounds the total cost of the whole sequence. It contains no probability. The statement has this form:
> For every sequence of n operations, starting from an empty structure, the total cost is at most T(n). The amortised cost per operation is T(n)/n.
Three features of this definition matter:
- It quantifies over all sequences. The guarantee is a worst case over sequences, not an average over inputs. No distribution assumption is needed.
- It averages over time, not over inputs. Expensive operations are paid for by the cheap operations around them.
- It says nothing about a single operation. An individual call can still cost O(n). The guarantee concerns the total.
Seeing the difference on a dynamic array
The following program records the cost of each append to a doubling array. A write costs 1. When the array is full, the append also copies every existing element, and the capacity doubles.
def append_costs(n):
size, capacity = 0, 1
costs = []
for _ in range(n):
cost = 1 # write the new element
if size == capacity:
cost += size # copy every element to a bigger array
capacity *= 2
size += 1
costs.append(cost)
return costs
costs = append_costs(16)
print(costs)
print("max:", max(costs))
print("total:", sum(costs), "average:", sum(costs) / len(costs))The output is:
[1, 2, 3, 1, 5, 1, 1, 1, 9, 1, 1, 1, 1, 1, 1, 1]
max: 9
total: 31
average: 1.9375The spikes sit at append numbers 2, 3, 5 and 9, which are the points where the array is full. The following chart shows the same data.
The three cost models read this data differently:
- Worst case: the largest bar. It grows with n, so a single append is O(n).
- Average case: there is no input distribution to average over. The cost does not depend on the values appended, only on the size at the time. The question does not arise.
- Amortised: the total of 31 over 16 appends stays below 2n. For this array, the total over n appends stays below 2n for every n, so the amortised cost is O(1). The next chapters prove this.
Notice that the amortised figure of about 2 per append is not the typical cost. Most appends cost 1. It is a bound on total work divided by the number of operations.
Comparing the three models
| Question | Worst case | Average case | Amortised |
|---|---|---|---|
| What does it bound? | One operation | Expected cost of one operation | Total cost of a sequence, divided by its length |
| Source of averaging | None | Random input (a distribution) | Time: cheap operations pay for costly ones |
| Needs an assumption? | No | Yes, about the input distribution | No |
| Can one operation exceed the bound? | No | Yes | Yes |
| Typical use | Real-time guarantees | Algorithm comparison under a workload model | Data structures with occasional rebuilds |
Common mistakes
Intermediate learners often make these errors:
- Treating amortised as average-case. The two are different. Amortised analysis has no probability and holds for the worst possible sequence. Average-case analysis depends on a distribution and can fail if the distribution is wrong.
- Assuming amortised O(1) means every operation is O(1). It does not. The bound applies to the total. A single append can still cost O(n).
- Analysing operations in isolation. The expensive append happens only because earlier appends filled the array. Amortised analysis ties the cost of a rare event to the history that caused it. If you analyse one operation without that history, you will wrongly conclude the structure is slow.
- Ignoring the starting state. The definition starts from an empty structure, or from a known state. A sequence that begins with a nearly full array can behave differently. Later chapters handle this with potential functions.
How this chapter fits the rest
The tutorial applies the amortised view to two structures. Chapters 2 to 7 analyse the dynamic array with three techniques: the aggregate method, the accounting method and the potential method. Chapters 8 to 12 apply the same ideas to hash tables, where resizing interacts with random hashing, so expected and amortised costs must be told apart. Chapter 13 closes with the situations where an amortised bound is not enough.
Exercises
Exercise
A list holds 1,000 items. A search for a value picks its target uniformly at random from those items and scans from the front. Name the model that gives the figure "about 500 comparisons", and say what assumption it relies on.
Show answer
This is the average-case model. It relies on the assumption that every position is equally likely to be the target. If users always search for the last item, every search costs 1,000 comparisons and the figure of 500 no longer holds.
Exercise
In the 16-append trace in this chapter, the largest single cost is 9 and the total cost is 31. State what the worst-case view and the amortised view each say about this structure, and explain why neither contradicts the other.
Show answer
The worst-case view says one append can be expensive: here it costs 9, and in general about n when the array is full. The amortised view says the total over n appends stays below 2n, so the cost per append averaged over the sequence is bounded by a constant. They do not conflict because the worst-case bound covers one operation, while the amortised bound covers the total. The expensive append occurs rarely, and the cheap appends before it have each done only one unit of work.
Exercise
A colleague says, "Appending is amortised O(1), so our request handler that appends to a list never takes more than constant time." What is wrong with this claim?
Show answer
Amortised O(1) bounds the total cost of a sequence, not each operation. A request that triggers a resize copies every element and takes O(n) time. The handler's worst-case latency is O(n) for that call, even though the average over many requests is constant.