Worst Case, Average Case and Amortized Cost
Distinguish best, worst and average-case cost across inputs from amortized cost across a sequence of operations, and prove why dynamic array doubling stays O(1) amortized.
Contentsand lesson path
On this page
- Why it matters
- Best, worst and average case are three separate functions
- Amortised analysis: worst-case over a sequence
- Trade-offs: when amortised O(1) is not good enough
- Check your understanding
- Apply it
- Review prompt
Lessons of Complexity Analysis
- Counting Steps Instead of Seconds Concept · 20 min
- Reading Loops: From Code to a Bound Worked example · 25 min
- Worst Case, Average Case and Amortized Cost Concept · 20 min
- Budgeting Operations from Input Limits Worked example · 15 min
- Lab: Timing Growth Curves with timeit Lab · 30 min
- Check: Predict, Then Measure Knowledge check · 8 questions
What you will learn
- Distinguish best, worst, average and amortized cost, and explain why appending to a dynamic array is amortized O(1).
Prerequisites: Python Foundations
01. Why it matters
Python lists are contiguous arrays in memory, so when a list fills its underlying buffer, list.append(x) must allocate a larger array and copy every existing reference across—an O(n) operation. Yet Python documentation still lists list.append as O(1). How can an operation that occasionally copies all n items still be called constant-time?
Confusion deepens because engineers often mix up two unrelated ideas: average-case cost (which depends on how inputs are distributed) and amortised cost (which guarantees the total cost of any sequence of operations). In this lesson you separate best, worst, average and amortised bounds so you can reason accurately about dynamic arrays, hash tables, and real-time latency limits.
02. Best, worst and average case are three separate functions
Many learners think "Big-O means worst case". That conflates the notation (O, Omega, Theta) with the case being analysed. For an algorithm on inputs of size n, there are three distinct cost functions, and each captures a different question about performance:
- Best case: the minimum steps over all inputs of size
n(for unsorted linear search, finding the target at index0, which isO(1)). Best case rarely drives capacity planning, yet it explains why an early-exit loop can look misleadingly fast on toy inputs. - Worst case: the maximum steps over all inputs of size
n(for linear search, the target is absent or sits at indexn - 1, which isTheta(n)). Worst case gives the hardest safety guarantee when untrusted users control inputs. - Average case: the expected steps over a stated probability distribution of inputs. If every slot in an
n-item list is equally likely to hold a present target, the search inspects(n + 1) / 2items on average, which isTheta(n)—notice it does not sit halfway asO(log n).
You can apply O(...), Omega(...), or Theta(...) to any of the three. For example, linear search has O(1) best-case time, O(n) average-case time under uniform target positions, and O(n) worst-case time.
03. Amortised analysis: worst-case over a sequence
Now return to list.append. Its cost does not depend on random input luck; even an adversary choosing the worst possible sequence of n appends hits the same resize schedule. Amortised cost means a worst-case bound averaged over a sequence of n operations: if any sequence of n appends does at most c * n total work, the amortised cost per append is O(1), even though single resizes cost O(n) in the calling thread (never in a hidden background thread, and never "ignored" as too rare to count).
How does the buffer avoid copying too often? Consider two resize policies starting from capacity 1:
- Fixed-step growth (
capacity += 16): an initial sensible idea if you want to avoid wasting unused slots on small lists. Unfortunately, every16appends trigger a full copy. Fornappends, you copy16 + 32 + 48 + ...elements—an arithmetic series whose sum is roughlyn^2 / 32, orTheta(n^2)total work (Theta(n)amortised per append). - Geometric growth (
capacity *= 2): each resize doubles the buffer, so resizes happen only at powers of two (1, 2, 4, 8, ...). Fornappends, the copied elements form a geometric series1 + 2 + 4 + ... + 2^k < 2n. Counting1write for each new item plus< 2ncopy writes gives< 3ntotal writes—O(n)total, orO(1)amortised per append.
append # : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
new cap : 1 2 4 4 8 8 8 8 16 16 16 16 16 16 16 16
copies : 0 1 2 0 4 0 0 0 8 0 0 0 0 0 0 0 (sum = 15 < 16)
writes : 1 2 3 1 5 1 1 1 9 1 1 1 1 1 1 1 (sum = 31 < 2*16)def simulate_appends(n: int, mode: str) -> tuple[int, int]:
"""Simulate n appends and return (total_writes, final_capacity)."""
capacity = 1
size = 0
writes = 0
for _ in range(n):
if size == capacity:
if mode == "fixed":
capacity += 16
elif mode == "double":
capacity *= 2
else:
raise ValueError(mode)
writes += size
size += 1
writes += 1
return writes, capacity
for n in (100, 1_000, 10_000):
fw, fc = simulate_appends(n, "fixed")
dw, dc = simulate_appends(n, "double")
print(f"n={n:<5} fixed_writes={fw:<9} double_writes={dw:<6} ratio={fw / dw:.1f}x")n=100 fixed_writes=443 double_writes=227 ratio=2.0x
n=1000 fixed_writes=32311 double_writes=2023 ratio=16.0x
n=10000 fixed_writes=3130625 double_writes=26383 ratio=118.7xLook closely at n = 100 -> 1,000 -> 10,000: multiplying n by 10 multiplies double_writes by roughly 10 (227 -> 2,023 -> 26,383), while fixed_writes explodes by roughly 100 each time (443 -> 32,311 -> 3,130,625). What if you changed "fixed" from + 16 to + 1,000? At n = 10,000 the constant 1,000 looks helpful, delaying resizes—yet at n = 10,000,000 it still triggers 10,000 full copies (O(n^2) total).
One important simplification to note: our simulation uses a 2x growth factor because the geometric sum < 2n is effortless to see by hand. CPython list objects actually grow by a smaller geometric fraction (roughly an eighth of the current length plus a small constant) to trade slightly more frequent resizes for lower unused memory overhead—keeping list.append at O(1) amortised while wasting far less spare capacity at large sizes.
04. Trade-offs: when amortised O(1) is not good enough
Doubling buys O(1) amortised appends at two real prices:
- Unused capacity: up to half the allocated buffer can sit empty right after a
2xresize (or ~1/8 in CPython). - Latency spikes on individual calls: amortised
O(1)guarantees the sum ofncalls, not every single call. In a hard real-time control loop, audio callback, or tail-latency-critical server handler where oneO(n)pause over a 50-million-element array violates a millisecond deadline, an amortised bound fails your requirement. In those situations you pre-allocate the needed capacity up front, use incremental background rehashing/copying, or pick a chunked structure that bounds single-operation work.
Similarly, keep worst-case vs amortised distinct when you move to How a Python List Grows and Hashing & Hash Tables: list.append is O(1) amortised even on adversarial inputs, whereas dict lookup is O(1) on average (or expected) and O(n) worst-case if all keys collide.
05. Check your understanding
06. Apply it
Extend simulate_appends in a scratch script to add a "one_half" mode that sets capacity to max(capacity + 1, int(capacity * 1.5)) and a "shrink" scenario that alternates append and pop around a power-of-two boundary with shrink threshold 0.5 vs 0.25. Print total writes at n = 10,000 and verify whether 0.25 eliminates thrashing.
Next, apply complexity classes directly to problem constraints in Budgeting Operations from Input Limits.
07. Review prompt
Without looking back:
- Why is
O(n)NOT a synonym for "worst case"? Give an example using linear search. - Prove in two sentences why
nappends withcapacity *= 2copy fewer than2nelements in total, whilecapacity += 16copiesTheta(n^2)elements. - Name one situation where an
O(1)amortised operation can still fail a system requirement.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.