Some operations are slow once in a while but fast almost every time. Amortized analysis asks a simple question: over a long run of operations, what does each one cost on average? A growing array is the classic case. Most appends take one step, but every so often the array doubles in size and copies everything.
In this lesson you will learn
- What “amortized cost” means, using a growing array you can run
- Why appending to a doubling array costs O(1) on average
- The three standard proofs: aggregate, accounting and potential
- How amortized cost differs from average-case cost
- Where you meet amortized costs in real libraries
Watch a Growing Array Pay for Itself
A C array has a fixed size. To let it grow, we keep a capacity. When the array is full, we allocate one twice as big and copy the old items across. The program below counts how many items each push has to copy.
#include <stdio.h>
#include <stdlib.h>
/* A growing array that doubles its capacity when it is full.
We count every element copy so we can see the real cost. */
typedef struct {
int *data;
size_t size, capacity;
long copies; /* total elements copied during resizes */
} Vec;
static int push(Vec *v, int value) {
if (v->size == v->capacity) {
size_t new_cap = v->capacity ? v->capacity * 2 : 1;
int *bigger = malloc(new_cap * sizeof *bigger);
if (!bigger) return 0;
for (size_t i = 0; i < v->size; i++) bigger[i] = v->data[i];
v->copies += (long)v->size;
free(v->data);
v->data = bigger;
v->capacity = new_cap;
}
v->data[v->size++] = value;
return 1;
}
int main(void) {
Vec v = {0};
for (int i = 1; i <= 9; i++) {
long before = v.copies;
push(&v, i);
printf("push %d: copied %ld, capacity now %zu\n",
i, v.copies - before, v.capacity);
}
free(v.data);
return 0;
}
Output
push 1: copied 0, capacity now 1
push 2: copied 1, capacity now 2
push 3: copied 2, capacity now 4
push 4: copied 0, capacity now 4
push 5: copied 4, capacity now 8
push 6: copied 0, capacity now 8
push 7: copied 0, capacity now 8
push 8: copied 0, capacity now 8
push 9: copied 8, capacity now 16
Most pushes copy nothing. A few pushes (2, 3, 5 and 9) copy everything, and each of those expensive pushes doubles the room, so the next one is twice as far away. That spacing is the whole trick.
Measuring the Average Cost per Push
Let us count every unit of work: one unit to write the new item, plus one unit for every item copied during a resize. Then divide by the number of pushes.
#include <stdio.h>
#include <stdlib.h>
static long total_work(long n) {
int *data = NULL;
long size = 0, capacity = 0, work = 0;
for (long i = 0; i < n; i++) {
if (size == capacity) {
capacity = capacity ? capacity * 2 : 1;
int *bigger = malloc(capacity * sizeof *bigger);
if (!bigger) exit(1);
for (long k = 0; k < size; k++) bigger[k] = data[k];
work += size; /* cost of copying */
free(data);
data = bigger;
}
data[size++] = (int)i;
work += 1; /* cost of the write itself */
}
free(data);
return work;
}
int main(void) {
long sizes[] = {10, 1000, 100000, 10000000};
printf("%10s %12s %14s\n", "n", "total work", "work per push");
for (int i = 0; i < 4; i++) {
long w = total_work(sizes[i]);
printf("%10ld %12ld %14.2f\n", sizes[i], w, (double)w / sizes[i]);
}
return 0;
}
Output
n total work work per push
10 25 2.50
1000 2023 2.02
100000 231071 2.31
10000000 26777215 2.68
Whether we push 10 items or 10 million, the work per push stays below 3. A single push can still cost millions of steps (the one that triggers a big resize), but averaged over the whole sequence the cost is a small constant. We write this as amortized O(1) per push.
Where the word comes from
In banking, to amortize a loan means to spread one big payment into many small instalments. Amortized analysis does the same with work: it spreads the cost of rare expensive steps across the many cheap steps around them.
Three Ways to Prove an Amortized Bound
Running the code shows the pattern; a proof shows it holds for every n. Textbooks use three methods. They reach the same answer from different directions.
1. Aggregate Method: Add Everything Up
Count the total cost of n operations, then divide by n.
- Writing the items costs n.
- Resizes copy 1, then 2, then 4, and so on, up to the largest power of 2 below n. That sum is less than 2n.
- Total work is therefore less than n + 2n = 3n.
- Average per push: less than 3n / n = 3, a constant.
2. Accounting Method: Charge a Little Extra
Pretend each push pays a fixed price of 3 coins. One coin pays for writing the item. The other two go into a savings jar.
When the array doubles from size k to 2k, it must copy k items. Since the last resize, k/2 new items have each saved 2 coins, which is k coins: exactly enough to pay for the copy. The jar never goes negative, so 3 coins per push is always enough. That price is the amortized cost.
3. Potential Method: Measure Stored-Up Work
Define a potential Φ that measures how “charged up” the structure is. For the growing array, a common choice is Φ = 2 × size − capacity. Cheap pushes raise Φ by 2. An expensive push releases that stored potential to pay for its copying. The amortized cost of an operation is its real cost plus the change in Φ, and for every push it works out to 3.
The potential method takes more practice, but it is the most powerful of the three. It is how data structures like splay trees and Fibonacci heaps are analysed.
A Second Example: Counting in Binary
Adding 1 to a binary number flips every trailing 1 to 0, then one 0 to 1. Going from 0111 to 1000 flips four bits, but most increments flip just one or two.
#include <stdio.h>
/* Binary counter: incrementing flips trailing 1s to 0, then one 0 to 1. */
int main(void) {
int bits[8] = {0};
long flips = 0;
int n = 16;
for (int step = 1; step <= n; step++) {
int i = 0;
while (i < 8 && bits[i] == 1) { bits[i] = 0; i++; flips++; }
if (i < 8) { bits[i] = 1; flips++; }
}
printf("%d increments caused %ld bit flips\n", n, flips);
printf("average flips per increment: %.2f\n", (double)flips / n);
return 0;
}
Output
16 increments caused 31 bit flips
average flips per increment: 1.94
The lowest bit flips on every increment, the next bit every second increment, the next every fourth, and so on. Added up, n increments cause fewer than 2n flips, so each increment costs amortized O(1), even though a single one can flip every bit.
Amortized vs Average-Case vs Worst-Case
These three ideas are easy to mix up. The key difference is whether chance is involved.
| Worst-case (per operation) | Average-case | Amortized | |
|---|---|---|---|
| Question asked | What is the slowest a single operation can be? | What is the expected cost, if inputs are random? | What is the cost per operation over any long sequence? |
| Uses probability? | No | Yes, needs an assumption about inputs | No, it is a guarantee |
| Growing array push | O(n) | Not usually stated | O(1) |
| Quick sort | O(n²) | O(n log n) | Not used |
An amortized bound is a promise about the total: any sequence of n operations costs at most n times the amortized cost. No luck is required.
Where You Meet Amortized Costs
- Python lists, C++
std::vector, JavaArrayList: appending is amortized O(1) because of capacity growth. - Hash tables: inserting is amortized O(1); the table occasionally rehashes into a bigger array.
- Stacks with multipop: popping many items at once can be slow, but each item can only be popped once after being pushed.
- Union-find (disjoint sets): with path compression, operations are almost constant amortized time.
For real-time systems, such as audio processing or games, the occasional slow operation can still cause a visible stutter. That is why some libraries let you reserve capacity in advance, for example vector.reserve(n) in C++.
Common Mistakes
- Calling amortized cost “average-case”. Average-case depends on random inputs; amortized cost holds for every sequence.
- Growing by a fixed amount. Adding, say, 10 slots each time makes n pushes cost O(n²) in total. You must grow by a factor (such as 1.5× or 2×) to get amortized O(1).
- Quoting amortized O(1) as a hard limit for one call. A single push can still take O(n). If every call must be fast, you need a different design.
- Shrinking too eagerly. If an array halves as soon as it is half empty, alternating push and pop at the boundary can resize on every call. Shrink only when it drops to a quarter full.
- Forgetting to check
malloc. A resize allocates memory, and allocation can fail. Always test the returned pointer.
Practice Exercises
Exercise 1. A growing array starts with capacity 1 and doubles when full. How many element copies happen in total during the first 16 pushes?
Show answer
Resizes happen at pushes 2, 3, 5 and 9, copying 1 + 2 + 4 + 8 = 15 items. (Push 17 would copy 16 more.)
Exercise 2. Suppose the array grows by adding 4 slots each time instead of doubling. Is push still amortized O(1)?
Show answer
No. Resizes happen every 4 pushes and copy 4, 8, 12, … items. The total grows like n²/8, so the amortized cost per push is O(n).
Exercise 3. In the accounting method, why is 2 coins per push not enough for a doubling array?
Show answer
One coin pays for writing the item, leaving only 1 coin saved per push. When the array doubles from k to 2k, only k/2 items have saved since the last resize, giving k/2 coins, but copying needs k. The jar would go negative.
Frequently Asked Questions
Is amortized O(1) the same as O(1)?
Not quite. O(1) worst-case means every single call is fast. Amortized O(1) means the total for n calls is O(n), even if a few calls are slow.
Why do arrays double instead of growing by 1.5?
Both give amortized O(1). Doubling resizes less often; growing by 1.5 wastes less memory. Different libraries pick different factors.
Which amortized method should I use in an exam?
The aggregate method is simplest when all operations are of one kind. Use accounting or potential when there are several operation types with different costs.
Does amortized analysis use probability?
No. It is a worst-case guarantee over a sequence of operations, which is what separates it from average-case analysis.
Summary
- Amortized cost is the total cost of a sequence divided by its length, guaranteed for every sequence.
- A doubling array makes push amortized O(1): total work for n pushes stays below 3n.
- Aggregate, accounting and potential methods all prove the same bound in different ways.
- Amortized is not average-case: no probability is involved.
- Grow by a factor, never by a fixed amount, to keep the amortized cost constant.
