Amortized Analysis — Data Structures

Amortized analysis calculates the average cost (number of steps) of each operation over a long run of operations. The example is push on a dynamic array, an…

Paying a motorway toll with a prepaid card: sometimes you wait in a long line to add money to the card. Then, dozens of times, you only tap it quickly at the gate. Ask "is paying the toll by card slow?" and the answer depends on what you look at: one payment, or a whole month.

Amortized analysis looks at the whole month. It calculates the average cost of each operation over a long run of operations, not the cost of a single one. Cost here means the number of steps. The best-known example is push on an array. Sometimes one push is expensive, like the long wait to add money. Most pushes are cheap, like a tap at the gate. On average, every push is still cheap.

A dynamic array: when full, move to an array twice as big

JavaScript arrays grow by themselves, so they are called dynamic arrays. Inside, an array like this has a capacity (the number of slots set aside) and a size (the number of slots in use). While there's a free slot, push only writes one value: it costs 1, so it's O(1).

When it's full, the array in the example below makes a new array twice as big, copies every old item over, then writes the new value. That costs size + 1: all the items copied, plus 1 write. That's O(n), with n the number of items. Moving to a bigger array like this is called a resize.

Here are 12 pushes onto an array whose capacity starts at 1, the same as in the Lab:

Push no. Copied Capacity after Cost
1 0 1 1
2 1 2 2
3 2 4 3
4 0 4 1
5 4 8 5
6 to 8 0 8 1 + 1 + 1
9 8 16 9
10 to 12 0 16 1 + 1 + 1

This is the code, a DynamicArray class:

class DynamicArray {
  constructor() {
    this.capacity = 1;
    this.size = 0;
    this.storage = new Array(this.capacity);
  }

  push(value) {
    let cost = 1;
    if (this.size === this.capacity) {
      this.capacity *= 2;
      const bigger = new Array(this.capacity);
      for (let i = 0; i < this.size; i++) {
        bigger[i] = this.storage[i];
      }
      this.storage = bigger;
      cost += this.size;
    }
    this.storage[this.size] = value;
    this.size++;
    return cost;
  }
}

const arr = new DynamicArray();
for (let i = 1; i <= 5; i++) {
  console.log(arr.push(i * 10));
}
// 1
// 2
// 3
// 1
// 5

The average stays below 3

The total cost of the 12 pushes in the table: 12 writes + 15 copies (1 + 2 + 4 + 8) = 27. The average is 27 / 12 = 2.25 per push. About 2, even though push number 9 alone costs 9.

Why does it stay small? Each resize copies twice as many items as the one before. But the next resize also comes twice as far away: in the table, resizes happen at push 2, 3, 5 and 9. All the copies for n pushes always add up to less than 2n. Add the n writes, and the total cost is less than 3n, so the average is below 3, however big n gets. 1,000 pushes cost 2,023 in total, far below 1,000 × 1,000.

That's what "push is amortized O(1)" means: most pushes are O(1), and sometimes one push is O(n) because of a resize, but the average over all the pushes stays O(1).

Amortized, worst case and average case

This table compares three ways to count the cost. The input is the data given to the code.

Term What it means Example
Worst case the most expensive a single operation can be one push that causes a resize: O(n)
Average case the average when the input is random, and unlucky input can stay slow a hash map lookup: O(1) on average if the keys spread evenly
Amortized the average per operation over any run of operations, not relying on lucky input push on a dynamic array: O(1)

Amortized O(1) examples: push on a dynamic array, set on a hash map (with an occasional rehash: the hash map adds buckets and spreads the keys again), and union-find (almost O(1)). A balanced BST (AVL, Red-Black) is different: every search is guaranteed O(log n), not O(1).

⚠️ An average that isn't a promise, and a resize gone wrong

💡 Why times two, not plus 4? If the capacity only grows by 4, a resize happens every 4 pushes, and each resize copies everything. 1,000 pushes take about 125,000 steps, 125 per push on average, and the bigger n gets, the bigger the average. Doubling makes resizes rarer as the array grows, and that's what keeps the average small.

TL;DR: Amortized analysis calculates the average cost (number of steps) of each operation over a long run of operations. The example is push on a dynamic array, an array that grows by itself. When it's full, it moves to an array twice as big and copies everything, so that one push is O(n). But these moves (resizes) get rarer, so n pushes cost less than 3n in total: push is amortized O(1). Worst case looks at the single most expensive operation. Average case is the average when the input (the data given to the code) is random. The amortized average holds for any order of operations. A balanced BST guarantees O(log n) per operation, not amortized O(1).

⚡ Full: move to an array twice as big

Write:

if (this.size === this.capacity) {
  this.capacity *= 2;
  const bigger = new Array(this.capacity);
  for (let i = 0; i < this.size; i++) {
    bigger[i] = this.storage[i];
  }
  this.storage = bigger;
  cost += this.size;
}

Meaning: A dynamic array is an array that grows by itself. capacity is the number of slots set aside, and size the number of slots in use. While there's a free slot, push only writes one value: its cost (number of steps) is 1. When it's full, this code doubles capacity, makes a new array bigger, then copies every old item from this.storage (the array that holds the items) into it. cost (the cost of this push, starting at 1) goes up by the number of items copied, so the total is size + 1: O(n).

⚡ The average stays small

Guess first: 12 pushes onto an array whose capacity starts at 1. What's the average cost per push?

2.25. The total is 12 writes + 15 copies (1 + 2 + 4 + 8) = 27, divided by 12. Yet push number 9 alone costs 9.

Meaning: A resize (moving to a bigger array) copies twice as many items as the one before, but the next resize also comes twice as far away. n pushes cost less than 3n in total. That's why push is called amortized O(1): most pushes are O(1), sometimes one is O(n), and the average stays O(1).

⚡ Amortized isn't a promise for each operation

Meaning: Worst case looks at the single most expensive operation. Average case is the average when the input (the data given to the code) is random. Amortized is the average over a run of operations, and it holds for any order of operations. But one push can still be O(n). So when every step has to finish on time, pick a structure whose worst case is fast too, such as a balanced BST.

What you will learn