Amortized Analysis
Amortized analysis finds the cost per operation averaged over a worst-case sequence of operations, so that a rare expensive step is paid for by the many cheap steps around it.
Cost Spread Over a Sequence
- Pick the sequence – consider any sequence of n operations on the structure, starting empty.
- Find the rare expensive step – identify which operations cost more than O(1) and what triggers them.
- Bound the total – show that expensive steps are rare enough, or prepaid enough, that the total is T(n).
- Divide – the amortized cost per operation is T(n) / n.
Amortized analysis is a way of measuring the cost of an operation by averaging it over a sequence of operations in the worst case. If any sequence of n operations costs at most T(n) in total, each operation has an amortized cost of T(n) / n, even if a few individual operations are much more expensive.
The word comes from finance: a large payment is amortized when it is spread over many small instalments. In the same way, the occasional expensive step of a data structure, such as resizing an array or rebuilding a tree, is spread over the cheap steps that made it necessary.
Amortized analysis gives a worst-case guarantee on the total. Unlike average-case analysis, it makes no assumption about the input distribution and uses no probability.
- Actual cost: what one operation really costs when it runs
- Amortized cost: the cost charged to it in the analysis; the charges must cover the total actual cost
- Used for dynamic arrays, hash tables, splay trees, union-find and Fibonacci heaps
Why Worst-Case per Operation Misleads
A dynamic array (Python list, C++ vector, Java ArrayList) doubles its capacity when full and copies every element into the new block. A push that triggers a resize on an array of n elements costs O(n).
A plain worst-case analysis multiplies that by the number of operations: n pushes, each O(n) in the worst case, gives O(n²). That bound is correct but far too pessimistic, because a resize cannot happen on every push. After doubling to 2k, the next k − 1 pushes are all cheap.
Counting what actually happens, n pushes copy 1 + 2 + 4 + … elements, a sum whose last term is below n, so fewer than 2n copies in total. The whole sequence is O(n) and each push is O(1) amortized. Amortized analysis exists to prove bounds like this.
- Amortized O(1) still allows a single slow operation; real-time systems may need a true worst-case bound
- The expensive step must be triggered by earlier cheap steps, or the averaging fails
Three Methods Compared
There are three standard techniques. All three prove the same kind of statement, and on the dynamic array they all give 3 per push. They differ in where the bookkeeping lives: in the total, in stored credits, or in a function of the structure's state.
| Method | Idea | Charge per operation | Condition to prove |
|---|---|---|---|
| Aggregate | bound the total cost of n operations | same for all: T(n) / n | T(n) holds for every sequence |
| Accounting (banker's) | overcharge cheap operations, store the surplus as credit | can differ by operation type | credit never goes negative |
| Potential (physicist's) | store the surplus as a potential Φ of the whole structure | actual + Φ(after) − Φ(before) | Φ(start) = 0 and Φ ≥ 0 always |
- Aggregate is simplest when every operation is of one kind
- Accounting is easiest to explain: the credit sits on specific elements
- Potential is the most general and is used for splay trees and Fibonacci heaps
Terms, operations, and practical uses
Core vocabulary
- Amortized costCost charged per operation so that charges cover the actual total of any sequence.
- Actual costWhat one operation really costs when it runs.
- CreditPrepaid cost stored by the accounting method; never negative.
- Potential ΦA function of the structure's state that stores prepaid work.
Formulas
- Aggregateamortized = T(n) / n.
- AccountingΣ ĉᵢ ≥ Σ cᵢ for every prefix.
- Potentialĉᵢ = cᵢ + Φ(Dᵢ) − Φ(Dᵢ₋₁), with Φ(D₀) = 0 and Φ ≥ 0.
- Dynamic arrayΦ = 2·size − capacity gives 3 per push.
Related lessons
- Time and Space ComplexityWorst, best and average case, before amortization.
- Big O NotationThe notation every amortized bound is written in.
- Static vs Dynamic ArraysThe doubling array this lesson analyses.
- Disjoint SetsUnion-find, whose α(n) bound is amortized.
Code in Python, C++ and Java
class DynamicArray:
def __init__(self):
self.capacity = 0
self.size = 0
self.items = []
self.copies = 0
def push(self, value):
copied = 0
if self.size == self.capacity:
# Full: allocate double the room and copy every element across.
self.capacity = max(1, 2 * self.capacity)
bigger = [None] * self.capacity
for i in range(self.size):
bigger[i] = self.items[i]
self.items = bigger
copied = self.size
self.copies += copied
self.items[self.size] = value
self.size += 1
return 1 + copied
def increment(bits):
flips = 0
i = 0
while i < len(bits) and bits[i] == 1:
bits[i] = 0
flips += 1
i += 1
if i < len(bits):
bits[i] = 1
flips += 1
return flips
def copies_growing_by_one(n):
# Growing by a fixed step copies the whole array on every push.
return n * (n - 1) // 2
def copies_doubling(n):
arr = DynamicArray()
for v in range(1, n + 1):
arr.push(v)
return arr.copies
print("Dynamic array with doubling, starting at capacity 0")
print("push cap copied cost total 3n bank")
arr = DynamicArray()
total = 0
for v in range(1, 10):
cost = arr.push(v)
total += cost
print(
f"{v:>4} {arr.capacity:>3} {cost - 1:>6} {cost:>4} {total:>5} "
f"{3 * v:>2} {3 * v - total:>4}"
)
print(f"total {total} for 9 pushes: amortized {total / 9:.2f} per push, bound 3")
print()
print("Binary counter, 16 increments")
bits = [0] * 5
total = 0
for k in range(1, 17):
flips = increment(bits)
total += flips
shown = "".join(str(b) for b in reversed(bits))
print(f"{k:>2} {shown} flips {flips} total {total:>2}")
print(f"total {total} flips for 16 increments: amortized {total / 16:.2f}, bound 2")
print()
print("Copies made: doubling vs growing by one")
for n in [9, 100, 1000]:
print(f"n = {n:>4} doubling {copies_doubling(n):>4} by one {copies_growing_by_one(n):>6}")#include <algorithm>
#include <cstdio>
#include <vector>
struct DynamicArray {
int capacity = 0;
int size = 0;
int* items = nullptr;
long long copies = 0;
~DynamicArray() { delete[] items; }
int push(int value) {
int copied = 0;
if (size == capacity) {
// Full: allocate double the room and copy every element across.
capacity = std::max(1, 2 * capacity);
int* bigger = new int[capacity];
for (int i = 0; i < size; i++) bigger[i] = items[i];
delete[] items;
items = bigger;
copied = size;
copies += copied;
}
items[size++] = value;
return 1 + copied;
}
};
int increment(std::vector<int>& bits) {
int flips = 0;
size_t i = 0;
while (i < bits.size() && bits[i] == 1) {
bits[i] = 0;
flips++;
i++;
}
if (i < bits.size()) {
bits[i] = 1;
flips++;
}
return flips;
}
long long copiesGrowingByOne(long long n) {
// Growing by a fixed step copies the whole array on every push.
return n * (n - 1) / 2;
}
long long copiesDoubling(int n) {
DynamicArray arr;
for (int v = 1; v <= n; v++) arr.push(v);
return arr.copies;
}
int main() {
std::printf("Dynamic array with doubling, starting at capacity 0\n");
std::printf("push cap copied cost total 3n bank\n");
DynamicArray arr;
int total = 0;
for (int v = 1; v <= 9; v++) {
int cost = arr.push(v);
total += cost;
std::printf("%4d %3d %6d %4d %5d %2d %4d\n", v, arr.capacity, cost - 1, cost, total, 3 * v,
3 * v - total);
}
std::printf("total %d for 9 pushes: amortized %.2f per push, bound 3\n\n", total, total / 9.0);
std::printf("Binary counter, 16 increments\n");
std::vector<int> bits(5, 0);
total = 0;
for (int k = 1; k <= 16; k++) {
int flips = increment(bits);
total += flips;
char shown[6] = {};
for (int i = 0; i < 5; i++) shown[i] = (char)('0' + bits[4 - i]);
std::printf("%2d %s flips %d total %2d\n", k, shown, flips, total);
}
std::printf("total %d flips for 16 increments: amortized %.2f, bound 2\n\n", total, total / 16.0);
std::printf("Copies made: doubling vs growing by one\n");
for (int n : {9, 100, 1000}) {
std::printf("n = %4d doubling %4lld by one %6lld\n", n, copiesDoubling(n), copiesGrowingByOne(n));
}
return 0;
}public class Main {
static class DynamicArray {
int capacity = 0;
int size = 0;
int[] items = new int[0];
long copies = 0;
int push(int value) {
int copied = 0;
if (size == capacity) {
// Full: allocate double the room and copy every element across.
capacity = Math.max(1, 2 * capacity);
int[] bigger = new int[capacity];
for (int i = 0; i < size; i++) bigger[i] = items[i];
items = bigger;
copied = size;
copies += copied;
}
items[size++] = value;
return 1 + copied;
}
}
static int increment(int[] bits) {
int flips = 0;
int i = 0;
while (i < bits.length && bits[i] == 1) {
bits[i] = 0;
flips++;
i++;
}
if (i < bits.length) {
bits[i] = 1;
flips++;
}
return flips;
}
static long copiesGrowingByOne(long n) {
// Growing by a fixed step copies the whole array on every push.
return n * (n - 1) / 2;
}
static long copiesDoubling(int n) {
DynamicArray arr = new DynamicArray();
for (int v = 1; v <= n; v++) arr.push(v);
return arr.copies;
}
public static void main(String[] args) {
System.out.println("Dynamic array with doubling, starting at capacity 0");
System.out.println("push cap copied cost total 3n bank");
DynamicArray arr = new DynamicArray();
int total = 0;
for (int v = 1; v <= 9; v++) {
int cost = arr.push(v);
total += cost;
System.out.printf("%4d %3d %6d %4d %5d %2d %4d%n", v, arr.capacity, cost - 1, cost, total, 3 * v,
3 * v - total);
}
System.out.printf("total %d for 9 pushes: amortized %.2f per push, bound 3%n%n", total, total / 9.0);
System.out.println("Binary counter, 16 increments");
int[] bits = new int[5];
total = 0;
for (int k = 1; k <= 16; k++) {
int flips = increment(bits);
total += flips;
StringBuilder shown = new StringBuilder();
for (int i = 4; i >= 0; i--) shown.append(bits[i]);
System.out.printf("%2d %s flips %d total %2d%n", k, shown, flips, total);
}
System.out.printf("total %d flips for 16 increments: amortized %.2f, bound 2%n%n", total, total / 16.0);
System.out.println("Copies made: doubling vs growing by one");
for (int n : new int[] {9, 100, 1000}) {
System.out.printf("n = %4d doubling %4d by one %6d%n", n, copiesDoubling(n), copiesGrowingByOne(n));
}
}
}Step through it
Running on push 1, 2, …, 9 into an array that starts at capacity 0
Aggregate Method
The aggregate method bounds the total actual cost T(n) of any sequence of n operations, then gives every operation the same amortized cost T(n) / n.
Dynamic array example. Start with capacity 0 and double when full. Push i resizes exactly when i − 1 is 0 or a power of two, copying i − 1 elements. Over n pushes the copies are 1 + 2 + 4 + … + 2^⌊log₂(n−1)⌋ < 2n, and the writes are n. So T(n) < 3n and each push costs O(1) amortized. The listing prints this for n = 9: 15 copies plus 9 writes = 24, under 3n = 27.
- Geometric sum: 1 + 2 + 4 + … + m < 2m
- Aggregate cost of n pushes: T(n) < 3n
- Weakness: it gives one amortized cost to every operation type
Accounting Method (Banker's Method)
The accounting method assigns each operation an amortized charge, which may be more or less than its actual cost. When the charge is higher, the difference is stored as credit in the data structure. When an operation costs more than its charge, stored credit pays the difference. The one rule: total credit must never go negative, so the charges always cover the actual cost.
Dynamic array example. Charge every push 3. One unit pays for writing the new element. The other two are stored on it: one pays to copy this element at the next resize, one pays to copy an element in the older half that already spent its credit. When the array doubles from k to 2k, the k/2 elements pushed since the last resize hold k credits, exactly enough to copy all k elements. The tracer shows the bank at each push: it never drops below zero.
- Amortized charge ĉ, actual cost c: credit changes by ĉ − c
- Invariant: Σ ĉ ≥ Σ c for every prefix of the sequence
- Different operations may get different charges, e.g. push 2 and multipop 0 on a stack
Potential Method
The potential method stores prepaid work as a potential function Φ that maps each state of the structure to a number. The amortized cost of the i-th operation is its actual cost plus the change in potential: ĉᵢ = cᵢ + Φ(Dᵢ) − Φ(Dᵢ₋₁).
Summing over n operations, the Φ terms telescope: Σ ĉᵢ = Σ cᵢ + Φ(Dₙ) − Φ(D₀). If Φ(D₀) = 0 and Φ(Dᵢ) ≥ 0, the total amortized cost is an upper bound on the total actual cost.
Dynamic array example. Let Φ = 2·size − capacity. A push without a resize costs 1 and raises Φ by 2: amortized 3. A push that resizes at size k costs k + 1; Φ falls from 2k − k = k to 2(k + 1) − 2k = 2, a change of 2 − k: amortized (k + 1) + (2 − k) = 3. Every push is O(1) amortized.
- Choose Φ to be large just before an expensive step and small just after it
- Φ must start at 0 and never go negative
- Splay trees use Φ = Σ log(subtree size); Fibonacci heaps use Φ = roots + 2·marked
Second Example: a Binary Counter
A k-bit binary counter is incremented by flipping the trailing 1s to 0 and the next 0 to 1. The worst single increment flips all k bits, so a naive bound for n increments is O(nk).
Aggregate: bit 0 flips on every increment, bit 1 on every second, bit j on every 2^j-th. The total over n increments is n + n/2 + n/4 + … < 2n, so each increment is O(1) amortized. The listing counts 31 flips for 16 increments.
Accounting: charge 2 per increment. One unit sets a bit to 1; the other stays on that 1 and pays for resetting it to 0 later. Every 1 bit always holds a credit, so the credit never goes negative. Potential: Φ = number of 1 bits gives the same result: an increment that resets t bits costs t + 1 and changes Φ by 1 − t, amortized 2.
- Worst single increment: O(k); amortized: O(1)
- Adding a decrement breaks the bound: alternating at 0111…1 and 1000…0 costs k every time
Amortized vs Average Case
Amortized and average-case analysis both produce a number that can be smaller than the worst case, but they mean different things. Average case is an expectation over a probability distribution of inputs, and an unlucky input can be slow. Amortized is a bound on the total of every sequence, with no probability, so no input can defeat it.
| Analysis | Averages over | Guarantee | Example |
|---|---|---|---|
| Worst case | nothing: one operation | every single operation | binary search: O(log n) |
| Average case | a distribution of inputs | only in expectation over inputs | quicksort with a fixed pivot: O(n log n) |
| Expected (randomized) | the algorithm's own random choices | in expectation, for every input | randomized quicksort, hashing |
| Amortized | a sequence of operations | total for every sequence, deterministic | dynamic array push: O(1) |
- Amortized O(1) does not mean every operation is O(1)
- Average O(1) does not mean every sequence is O(n)
- Hash tables are both: expected O(1) lookups, amortized O(1) resizing
Where Amortized Bounds Appear
Amortized analysis is how the running times of many standard data structures are proved. In each case, a rare expensive step keeps the structure in a shape that makes later operations cheap.
- Dynamic array: resizing and copying is rare, so push is O(1)
- Hash table: rehashing into a table twice the size keeps insert O(1) expected amortized
- Splay tree: splaying a deep node to the root makes access O(log n)
- Union-find: path compression on a long path gives O(α(n)) per operation
- Fibonacci heap: consolidating the root list only in extract-min gives O(1) decrease-key and O(log n) extract-min
- Monotonic stack and a queue built from two stacks: each element is pushed and popped once, O(1) per element
- Pattern: every element pays a constant amount on the way in to cover its later work
- Practise it: Min Stack and Implement Queue using Stacks