Explain why some expensive steps average out to a small cost per operation.
Use it when most operations are cheap and a few are expensive, and you want the cost of a whole run. Signal words: amortised O(1), doubling, resize, occasionally expensive.
Start fix a sequence of n operations, and decide what you count: copies, flips, steps.
Step add up the cost of every operation in the run, the cheap ones and the expensive ones.
Stop divide the total by n. Check the claim with an argument, such as the sum 1 + 2 + 4 + ... or a credit that stays at or above 0.
It does not bound one operation, and it does not use probability. A single push can still copy half of everything.
Cost: one sum over the run. Both templates below take about log n steps.
In this lesson you learn why a step that is sometimes very expensive can still be cheap on average over a run. You learn two ways to explain it correctly, and where the explanation stops holding.
You work on a monitoring system. Alerts are appended to a buffer, one at a time. When the buffer is full, the system allocates a buffer twice as large and copies every alert across.
Most appends are instant. An append that finds the buffer full copies everything, and the dashboard stalls for a moment. Arrays in memory, in the Array Arcade, already show the growth facts. Here you ask what an append costs overall.
Your team lead says: Is an append O(1), or does the copying make it O(n)?
So the task is this: count the work of a whole run of appends, and decide what each append costs on average.
A shop keeps mugs on a shelf. When the shelf is full, the owner buys a shelf twice as big and moves every mug across. Moving is slow, but it happens only after the shelf has filled.
The mugs moved are never more than the mugs put on the shelf since the last move, plus the ones moved before. Over a year, each mug is moved only a few times.
Like a shelf that doubles: moving every mug is slow, but it happens only after the shelf has filled, so each mug moves a few times.
Before you write code, count the copies of ten pushes by hand. The buffer starts with room for 1 item and doubles when a push finds it full.
Solve it by hand: Copies of a doubling buffer. The hand-solve sheet loads in your browser.
A resize happens when a push finds the buffer full, and it copies every item inside.
| Push | Buffer before | Copies | Buffer after |
|---|---|---|---|
| 2 | full at 1 | 1 | room for 2 |
| 3 | full at 2 | 2 | room for 4 |
| 5 | full at 4 | 4 | room for 8 |
| 9 | full at 8 | 8 | room for 16 |
The other six pushes copy nothing. The total is 1 + 2 + 4 + 8 = 15.
Start with a correct version. Push the items one at a time, and when the buffer is full, build a new one twice the size and copy.
def push_all(items):
buffer, size, capacity, copies = [None], 0, 1, 0
for item in items: # each push
if size == capacity: # full: resize
buffer = buffer + [None] * capacity # twice the room
copies += size # every item is copied across
capacity *= 2
buffer[size] = item
size += 1
return copiesIt is correct. The cost of one push depends on whether it finds the buffer full.
Now check the real size.
The system appends 1,000,000 alerts.
Here is the count, from running the code:
Predict the cost
Q A buffer grows by 10 slots each time it is full. About how many items do 1,000,000 pushes copy?
Answer: C
The buffer resizes about 100,000 times, and the copies add up to 49,999,600,000.
You decided this with a count over the whole run, not with the cost of one push.
Can a growth rule keep the total small? Compare three rules over the same pushes. Each count comes from running the buffer, starting with room for 1 item.
| Pushes | Doubling | Growing by half | Growing by 10 |
|---|---|---|---|
| 1,000 | 1,023 | 2,120 | 49,600 |
| 100,000 | 131,071 | 276,492 | 499,960,000 |
| 1,000,000 | 1,048,575 | 2,099,719 | 49,999,600,000 |
Growing by a constant factor, such as 2 or 1.5, keeps the copies in proportion to the pushes. Growing by a fixed amount makes the copies grow like n squared. For 1,000 pushes that is 49.6 copies per push, and for 100,000 pushes it is 4,999.6.
Exercise · Predict the output: How many copies when the buffer grows by 2?. A buffer starts with room for 2 items and grows by 2 slots each time a push finds it full. The code counts the items copied over 8 pushes. What does it print?
capacity = 2
size = 0
copies = 0
for push in range(8):
if size == capacity:
copies += size
capacity += 2
size += 1
print(copies)In 20 pushes into the doubling buffer, only 5 pushes copy: the 2nd, 3rd, 5th, 9th and 17th. They copy 1, 2, 4, 8 and 16 items, 31 in all. Tripling instead of doubling copies 797,161 items in 1,000,000 pushes against 1,048,575, but it ends with 594,323 idle slots against 48,576.
Race: Total cost of a run of operations. The operation counter loads in your browser.
The race counts the total cost at n = 10, 100, 1,000 and 10,000. At 10,000, doubling copied 16,383 items, a counter flipped 19,995 bits, and growing by 10 copied 4,996,000.
Over a thousand pushes a doubling buffer copies 1,023 items, growing by half copies 2,120, and growing by ten copies 49,600.
A binary counter is incremented 10 times, and each increment flips the bits that change. The player asks you to predict the total flips as each bit is counted.
Dry run: Predict each step: flips of a binary counter. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Bit | It flips every | Flips in 10 increments | Total so far |
|---|---|---|---|
| 0 | 1 increment | 10 | 10 |
| 1 | 2 increments | 5 | 15 |
| 2 | 4 increments | 2 | 17 |
| 3 | 8 increments | 1 | 18 |
That is 18 flips for 10 increments, less than 2 for each.
For 16 increments, the flips of each are 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5. The total is 31.
Shrinking the buffer needs care. A buffer of 1,024 items that halves when half full copied 1,024,000 items in 1,000 alternating pushes and pops. Halving at a quarter full copied 1,024.
The aggregate method counts the total cost of n operations and divides by n. For the buffer, the copies are fewer than 2n, so with the write the work is below 3n and each push costs less than 3 on average.
The accounting method charges every push a fixed price, 3 units. One unit pays for the push itself, and 2 are saved on the new item as credit. A resize at k items copies k items, and the newer k/2 items carry 2 credits each, which is k. So the credit pays for every copy.
In a counted run with a charge of 3, the saved credit never went below 0 and reached 977 at 1,000 pushes. With a charge of 2 it fell to -510, so 2 is not enough.
These explanations say nothing about random inputs. They hold for every sequence of pushes.
Here is the rule that keeps an amortised claim honest. Both templates use it.
Amortised cost is the total cost of a whole sequence of operations divided by their number, a guarantee for every sequence with no randomness.
An amortised claim is about a run, not about one step. It also needs an argument that the total is small, such as the sum of the copies or a credit that never goes negative.
Use it when most operations are cheap and a few are expensive, and you want the cost of a whole run. Signal words: amortised O(1), doubling, resize, occasionally expensive.
Start: fix a sequence of n operations, and decide what you count: copies, flips, steps.
Step: add up the cost of every operation in the run, the cheap ones and the expensive ones.
Stop: divide the total by n. Check the claim with an argument, such as the sum 1 + 2 + 4 + ... or a credit that stays at or above 0.
It does not bound one operation, and it does not use probability. A single push can still copy half of everything.
Cost: one sum over the run. Both templates below take about log n steps.
The function returns the total items copied after a number of pushes. The buffer starts with room for 1 item, and a push that finds it full doubles it.
def copies_for_pushes(pushes):
# [1] The buffer starts with room for 1 item, and no copies have been made.
capacity = 1
copies = 0
# [2] A push finds the buffer full while the pushes outnumber the capacity.
while pushes > capacity:
# [3] The resize copies every item in the buffer, which is capacity items.
copies += capacity
# [4] The new buffer has twice the room.
capacity *= 2
# [5] Return the total number of copies.
return copiespublic long copiesForPushes(int pushes) {
// [1] The buffer starts with room for 1 item, and no copies have been made.
long capacity = 1;
long copies = 0;
// [2] A push finds the buffer full while the pushes outnumber the capacity.
while (pushes > capacity) {
// [3] The resize copies every item in the buffer, which is capacity items.
copies += capacity;
// [4] The new buffer has twice the room.
capacity *= 2;
}
// [5] Return the total number of copies.
return copies;
}long long copiesForPushes(int pushes) {
// [1] The buffer starts with room for 1 item, and no copies have been made.
long long capacity = 1;
long long copies = 0;
// [2] A push finds the buffer full while the pushes outnumber the capacity.
while (pushes > capacity) {
// [3] The resize copies every item in the buffer, which is capacity items.
copies += capacity;
// [4] The new buffer has twice the room.
capacity *= 2;
}
// [5] Return the total number of copies.
return copies;
}function copiesForPushes(pushes) {
// [1] The buffer starts with room for 1 item, and no copies have been made.
let capacity = 1;
let copies = 0;
// [2] A push finds the buffer full while the pushes outnumber the capacity.
while (pushes > capacity) {
// [3] The resize copies every item in the buffer, which is capacity items.
copies += capacity;
// [4] The new buffer has twice the room.
capacity *= 2;
}
// [5] Return the total number of copies.
return copies;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The push that copies nothing. One push into the empty buffer must copy nothing, yet this function reports a copy. Which line is wrong?
def copies_for_pushes(pushes):
capacity = 1
copies = 0
while pushes >= capacity:
copies += capacity
capacity *= 2
return copiesA binary counter adds 1 each time by flipping the lowest bits that change. Bit 0 flips on every increment, bit 1 on every second one, bit 2 on every fourth, and so on. The function adds up the flips of every bit.
def flips_for_increments(n):
# [1] No flips have been counted yet.
total = 0
step = 1
# [2] A bit that flips every step increments flips n divided by step times in n increments.
while step <= n:
total += n // step
# [3] The next bit flips half as often.
step *= 2
# [4] Return the total number of flips.
return totalpublic long flipsForIncrements(int n) {
// [1] No flips have been counted yet.
long total = 0;
long step = 1;
// [2] A bit that flips every step increments flips n divided by step times in n increments.
while (step <= n) {
total += n / step;
// [3] The next bit flips half as often.
step *= 2;
}
// [4] Return the total number of flips.
return total;
}long long flipsForIncrements(int n) {
// [1] No flips have been counted yet.
long long total = 0;
long long step = 1;
// [2] A bit that flips every step increments flips n divided by step times in n increments.
while (step <= n) {
total += n / step;
// [3] The next bit flips half as often.
step *= 2;
}
// [4] Return the total number of flips.
return total;
}function flipsForIncrements(n) {
// [1] No flips have been counted yet.
let total = 0;
let step = 1;
// [2] A bit that flips every step increments flips n divided by step times in n increments.
while (step <= n) {
total += Math.floor(n / step);
// [3] The next bit flips half as often.
step *= 2;
}
// [4] Return the total number of flips.
return total;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Break it: Find the run whose top bit goes missing. This counts the bit flips of n increments of a binary counter. Find an n where it gives the wrong total.
def flips_for_increments(n):
total = 0
step = 1
while step < n:
total += n // step
step *= 2
return totalFlips of a binary counter: bit k flips every 2 to the k increments, so n increments flip it n over that step times.
You can state any amortised bound in four steps.
A counter is incremented 1,000,000 times. Template 2 gives 1,999,993 flips, fewer than 2 for each increment, although one increment flipped 20 bits.
The expensive increments are rare. Bit 19 flips only 1 time in 524,288 increments.
Real data brings edge cases.
For pushes = 0 and for pushes = 1 the template returns 0. The first push fits in the room the buffer starts with.
For pushes = 4 the template returns 3, and for pushes = 5 it returns 7. The fifth push is the one that finds the buffer full and copies 4 items.
For n = 1024 the counter template returns 2,047. The bit that flips once is bit 10, and the total is 2n - 1.
A counter with bits = 10 that wraps to 0 flipped 2,046 bits over one full cycle of 1,024 increments, counted by running it. That is 2^11 - 2, and still about 2 for each increment.
This version says each push may copy n items, so 1,000 pushes cost 1,000 × 513 steps.
Counterexample: the worst single push in 1,000 pushes cost 513 steps, but all 1,000 pushes cost 2,023 steps: 1,000 writes and 1,023 copies. The product, 513,000, is about 250 times too high.
This version says growing the buffer by 10 slots is as good as doubling, because both resize only when full.
Counterexample: over 1,000 pushes, doubling copied 1,023 items and growing by 10 copied 49,600. Over 100,000 pushes the gap is 131,071 against 499,960,000.
Two wrong claims: charging every push the worst case, and growing by a fixed amount as if it were doubling.
This version charges every push 2 units, one for the write and one saved, and says the credit pays for the copies.
Counterexample: with a charge of 2, the credit fell to -510 during 1,000 pushes, so it cannot pay for the copies. A charge of 3 stayed at or above 0.
This version says an amortised O(1) push never takes long.
Counterexample: in 1,000 pushes the 513th copied 512 items, and in 1,000,000 pushes one push copied 524,288. Amortised bounds the total of a run, not one push.
A system with a hard deadline for every append cannot use the amortised cost. One append in 1,000 still copied 512 items.
For such a system, use the worst case of one operation. Avoid the copy by sizing the buffer in advance, or by growing it a little at a time in the background.
Your team lead brings three product changes. Each one asks how the total moves.
The buffer grows by one and a half times, rounded up, instead of doubling. Over 1,000,000 pushes it copies 2,099,719 items, about twice the doubling total, and still fewer than 3 for each push.
The buffer starts with room for 1,000 items. Over 1,000,000 pushes it copies 1,023,000 items instead of 1,048,575, and the first 1,000 pushes copy nothing.
A Python list does not double. On one laptop (CPython 3.11.6) its allocated size changed 28 times over 1,000 appends, at the lengths 5, 9, 17, 25 and 33 among others. It grows by about 1.125 times at large sizes, as Arrays in memory measured. That is still a constant factor, so appends stay amortised O(1).
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate why appending to a doubling buffer is amortised O(1) although one append can copy everything. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
A resize copies k items only after about k pushes, so the copies add up to fewer than 2n. With the writes, the work is below 3n.
That is the aggregate view: total over the run, divided by n. For the accounting view, each push is charged 3, and the saved credit pays for every copy.
It holds for every sequence. It does not bound one push: one push still copies half of everything.
Appending to a doubling buffer is amortised constant. Most pushes cost one write. A push that finds the buffer full copies everything across and doubles the room.
I count the whole run. A resize at k items happens only after k pushes, so the copies are 1, 2, 4 and so on. They add up to fewer than twice the pushes. A million pushes copied 1,048,575 items in a counted run.
The accounting view charges each push 3. One pays for the write and two are saved. The newer half of the items carries enough credit to pay for all the copies.
This holds for every sequence, with no randomness. It does not bound one push. Growing by a fixed amount instead of doubling is not constant: it copied 49,600 items in a thousand pushes.
Checkpoint · Amortised cost
Q1/10 What is the amortised cost of an operation?
Answer: C
It is a total over a whole sequence divided by n, and it holds for every sequence.
Q2/10 A buffer that doubles when full receives 10 pushes, starting with room for 1 item. How many items does it copy in all?
Answer: C
The resizes copy 1, 2, 4 and 8 items.
Q3/10 A doubling buffer receives 1,000,000 pushes. About how many items does it copy per push?
Answer: C
The total was 1,048,575 copies, so fewer than 2 for each push.
Q4/10 The 513th push of 1,000 copied 512 items. What does this say about amortised O(1)?
Answer: B
Amortised bounds the total, not one operation.
Q5/10 A buffer grows by 10 slots each time it is full. What happens to the copies per push as n grows?
Answer: B
A fixed increment resizes ever more often per item, so the copies grow like n squared.
Q6/10 In the accounting method, how much is a push charged in the lesson, and why does 2 fail?
Answer: C
The saved credit must pay for every copy, and with 2 it went below 0.
Q7/10 A binary counter is incremented 1,000 times. About how many bit flips in all?
Answer: C
Bit 0 flips 1,000 times, bit 1 flips 500 times, and so on.
Q8/10 Does the amortised bound for a doubling buffer depend on the input being random?
Answer: A
No probability is used.
Q9/10 A service must answer every append within a strict deadline. Which cost do you check?
Answer: C
One append in 1,000 still copied 512 items.
Q10/10 A library grows its lists by 1.5 times instead of 2. What happens to the amortised cost?
Answer: B
Any constant factor above 1 keeps the copies in proportion to the pushes.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Cost of a growing buffer | Rides | Easy | Total copies of a doubling buffer from a given start |
| 2 | Total work of repeated doubling | Freight | Medium | Doubling against a fixed increment, with the closed form |
| 3 | Amortised cost of a counter | Chat | Medium | Total bit flips of a counter that wraps |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.