Sub topic 1
Three Ways to Talk About Cost
Prerequisites
Assume you know Big-O notation, fixed-size arrays, indexing, hash tables, and basic Python. You should also know that allocating or copying one element costs constant time.
Worst-Case, Average-Case, and Amortised Cost
These cost models answer different questions:
- Worst-case cost is the maximum cost of one operation.
- Average-case, or expected, cost is the average over a probability distribution, such as random hash values.
- Amortised cost is the average cost over any sequence of operations. It does not assume random input.
An operation can have a high worst-case cost but a small amortised cost. This happens when expensive operations are rare and pay for themselves across many cheap operations.
How a Dynamic Array Grows
A dynamic array stores elements in a fixed-size array. When that array is full, it allocates a larger array and copies the existing elements. With doubling, the capacities are 1, 2, 4, 8, and so on.
data = [None] * 1
data = [None] * 2 # copy the old element
data = [None] * 4 # copy two elementsMost appends write one element, so they cost O(1). An append that triggers resizing costs O(n), where n is the current number of elements.
Aggregate Method: Totalling the Cost of n Appends
The aggregate method totals the cost of an entire sequence and divides by its length.
For n appends, ordinary writes cost n. Copies happen when capacities double:
- Copy 1 element.
- Copy 2 elements.
- Copy 4 elements.
- Continue up to the largest power of two below n.
The total number of copied elements is less than:
1 + 2 + 4 + ... + n = 2n - 1
Therefore, the total cost is less than 3n. The amortised cost per append is less than 3, which is O(1), even though some individual appends cost O(n).
Accounting Method: Charging Each Append
The accounting method assigns each append a fixed charge. Charge 3 units:
- 1 unit pays for the append itself.
- 2 units are saved as credit on the inserted element.
When resizing occurs, the saved credits pay for copying old elements. Before an element is copied, it has accumulated enough credit. Thus every append pays its share, and the amortised charge remains O(1).
Exercise
Why does doubling produce O(1) amortised append cost?
Show answer
The total copies form a geometric series smaller than 2n, so n writes plus fewer than 2n copies cost O(n) total.