Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 20 min · revision 1

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

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 index 0, which is O(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 index n - 1, which is Theta(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) / 2 items on average, which is Theta(n)—notice it does not sit halfway as O(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, every 16 appends trigger a full copy. For n appends, you copy 16 + 32 + 48 + ... elements—an arithmetic series whose sum is roughly n^2 / 32, or Theta(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, ...). For n appends, the copied elements form a geometric series 1 + 2 + 4 + ... + 2^k < 2n. Counting 1 write for each new item plus < 2n copy writes gives < 3n total writes—O(n) total, or O(1) amortised per append.
Text · copy counts up to n = 16 under doubling (1 -> 2 -> 4 -> 8 -> 16)
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)
Python · comparing fixed-step vs doubling growth writes
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")
Expected output
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.7x

Look 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 2x resize (or ~1/8 in CPython).
  • Latency spikes on individual calls: amortised O(1) guarantees the sum of n calls, not every single call. In a hard real-time control loop, audio callback, or tail-latency-critical server handler where one O(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

Practice check · 3 questions

Cases and amortised bounds

Check your mental model of cases vs amortised sequences.

Q1. Suppose a dynamic array doubles when full, and also halves its capacity immediately whenever `size == capacity // 2` after a `pop()`. What happens if you alternate `append` and `pop` right at capacity `n`?
Q2. A dynamic array multiplies its capacity by `1.5` instead of `2` when it is full. Right after the resize that happens at `1,000,000` items, about how many slots sit unused, and what is the amortised cost of `append`?
Q3. An audio callback appends one sample to a Python list each time it runs, and every call must finish within `1 ms`. The list grows to several million samples. Is amortised `O(1)` append enough to meet the deadline?
Practice only: not graded, not saved, not evidence.

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:

  1. Why is O(n) NOT a synonym for "worst case"? Give an example using linear search.
  2. Prove in two sentences why n appends with capacity *= 2 copy fewer than 2n elements in total, while capacity += 16 copies Theta(n^2) elements.
  3. 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.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check