Amortized Analysis
Why an expensive step now and then still averages out: aggregate, accounting and potential.
Appending to a Python list sometimes copies the whole list, an operation that costs . Yet a million appends take about as long as a million cheap ones. Amortized analysis explains why with a guarantee, not a hope: no sequence of operations, however adversarial, can make the average cost per operation grow.
What you’ll learn
- Define amortized cost, and distinguish it from average-case and expected cost.
- Bound the total cost of a sequence by the aggregate method: dynamic arrays, binary counters, multipop stacks.
- Assign amortized costs with the accounting method and with a potential function, and check the conditions that make them valid.
- Recognize amortized linear time in monotonic stacks, two pointers and similar loops, and know what amortized bounds do not promise.
Expensive sometimes, cheap on average
A dynamic array keeps its elements in one block of contiguous memory with some spare room, its capacity. An append writes into the spare room in time. When the block is full, the array allocates a bigger one and copies every element over: one append then costs .
If the new block is twice as large, copies are rare, and they get rarer as they get bigger. Amortized analysis makes this precise: if every sequence of operations costs at most in total, each operation has amortized cost , even when single operations cost far more.
class DynArray:
def __init__(self):
self.cap, self.n, self.data = 0, 0, []
self.writes = 0 # element writes, to measure the cost
def append(self, x):
if self.n == self.cap: # full: allocate twice the room, copy everything
self.cap = max(1, 2 * self.cap)
new = [None] * self.cap
for i in range(self.n):
new[i] = self.data[i]
self.writes += self.n
self.data = new
self.data[self.n] = x
self.n += 1
self.writes += 1We count element writes: one per append, plus one per element copied during a resize. Real libraries grow by different factors (CPython lists by about an eighth plus a constant, Java's ArrayList by half, GCC's std::vector by two), and any constant growth factor above 1 gives the same amortized bound.
Starting from an empty DynArray (capacity 0, then 1, 2, 4, …), how many element writes do 17 appends make in total?
Show the answer
48
Resizes happen at appends 2, 3, 5, 9 and 17, copying elements; with the 17 writes of the new elements that is 48. The 17th append alone writes 17 elements, but the average is under 3, and it stays under 3 for every .
The aggregate method
The aggregate method bounds the total cost of operations directly and divides by . Three classic examples:
Dynamic array with doubling. The resizes copy elements, each at most the current size, so the copies sum to less than ; add writes of new elements:
Binary counter. Incrementing a counter from 0 flips the trailing 1s to 0 and one 0 to 1. A single increment can flip all bits, but bit flips only every -th time, times in increments:
Multipop stack.
MULTIPOP(k)pops up to elements and can cost once. But each element is popped at most once after being pushed once, so pops never outnumber pushes:
| Structure | Worst single operation | Total for operations | Amortized per operation |
|---|---|---|---|
| dynamic array, doubling | (a resize) | ||
| binary counter, increments only | for bits | flips | |
| stack with multipop |
The accounting method
The accounting method charges each operation a fixed amortized cost. When the charge exceeds the actual cost, the difference is stored as credit on specific elements of the structure; expensive operations are paid from stored credit. The rule that makes it valid: total credit never goes negative. Then the total charged is at least the total actual cost.
For the dynamic array, charge 3 per append. One unit pays for writing the element; two units are left on it as credit. When a full array of capacity doubles, the elements appended since the last resize hold units of credit: exactly enough to copy all elements, the old ones included. Credit is back to zero, and the next resize is again paid in advance.
For the binary counter, charge 2 per increment: one unit pays for setting a bit to 1, and the other stays on that bit to pay for resetting it to 0 later. Every 1 bit always carries one unit, and the cascade of resets that an increment triggers is prepaid. For the multipop stack, charge 2 per push and 0 per pop: the extra unit on each element pays for its eventual pop, whichever operation pops it.
Think first Why would charging only 2 per append not work for the doubling array?
With 2 per append, each new element arrives with 1 unit of credit. At the resize from to , only the newest elements carry credit, units in all, but copying costs . The old elements spent their credit at the previous resize, so the newcomers must pay for them too: 2 units of credit each, 3 in total per append.
The potential method
Sum the amortized costs over operations; every intermediate potential cancels:
So the amortized costs bound the actual total whenever the final potential is at least the initial one. The usual way to ensure it is and always:
Dynamic array, with , which is 0 for the empty array and never negative afterwards, since a doubling array is always at least half full. An append without a resize costs 1 and raises by 2. An append into a full array of capacity costs , while falls from to :
Binary counter, with = the number of 1 bits. An increment that resets trailing 1s and sets one 0 costs and changes by :
The potential method is the accounting method with the credit written as a function of the state rather than of the history. That makes it the tool of choice for complex structures: splay trees, Fibonacci heaps and union–find are all analyzed with clever potentials.
Which potential shows that push, pop and MULTIPOP(k) all have amortized cost ?
- for every state
- the number of operations performed so far
- the number of elements on the stack
Show the answer
C. the number of elements on the stack
A push costs 1 and raises by 1, so . A pop costs 1 and lowers by 1, so . MULTIPOP removing elements costs and lowers by : . And starts at 0 and never goes negative.
What amortized bounds do not promise
Latency. An amortized bound says nothing about one operation. The append that resizes an array of elements copies all of them, a pause of tens to hundreds of milliseconds. That is harmless in a batch job and unacceptable in a game loop, a trading system or a hard real-time controller; the Optimal lessons show how to spread the work out.
Robustness. The analysis assumed the operations given. Add one more, and an adversary may return the structure to an expensive state again and again. A -bit counter with decrement as well as increment can alternate between and , flipping all bits every time: for operations. A dynamic array that halves as soon as it is half full can be pushed back and forth across that boundary.
A third trap is persistence: if old versions of a structure stay usable, an adversary can rerun an expensive operation on the same old version as often as it likes, and the credit paid in advance is spent many times. Amortized bounds assume each state is used once, in sequence.
Recognizing it
Amortization hides in loops whose inner work looks unbounded but is paid for by progress elsewhere. The signals:
- each element enters and leaves a structure at most once (a stack, a queue, a window);
- a pointer or a counter only moves one way, so the total of its moves is bounded even if one step moves it far;
- a structure is rebuilt occasionally, at sizes that grow geometrically.
The classic case is the monotonic stack. To find each element's next greater element, keep a stack of indices still waiting for an answer; a new value pops every smaller value it is the answer for.
def next_greater(a):
"""res[i] = the first a[j] > a[i] with j > i, or -1."""
res = [-1] * len(a)
stack = [] # indices still waiting for an answer
for i, x in enumerate(a):
while stack and a[stack[-1]] < x:
res[stack.pop()] = x # x is the first greater value for that index
stack.append(i)
return res
print(next_greater([2, 7, 3, 5, 4, 6, 1, 8])) # [7, 8, 5, 6, 6, 8, 8, -1]The while loop can pop many indices at once, so one iteration of the for loop may cost . But every index is pushed once and popped at most once: at most stack operations in total, time.
| Problem (in brief) | Why the total is bounded | Total cost |
|---|---|---|
| Next greater element; days until a warmer day | each index is pushed once and popped at most once | |
| Longest substring without a repeated character | two pointers: left and right each move forward at most times | |
| Maximum of every window of length | monotonic deque: each index enters and leaves once | |
| KMP pattern matching | the matched length rises by at most 1 per text character, so it can fall at most times in total | |
| Hash table with resizing | rehash everything when the load factor passes a constant, doubling the table | amortized per insert (expected, over the hashing) |
Common bugs
list.pop(0)orlist.insert(0, x)in a Python loop: each shifts the whole list, per call. Usecollections.deque.- Building a string with
+=in a loop in a language with immutable strings (Java, C#): in total. Use a builder, or collect the pieces and join them once. - Resetting a pointer that the analysis assumes only moves forward.
- Shrinking a buffer as soon as it is half empty, which thrashes.
- Citing an amortized bound where a per-operation deadline is required.
For each of daily temperatures, find how many days pass until a strictly warmer day. Which approach fits the limits?
- For each day, scan forward until a warmer day appears
- Sort the temperatures and binary search for each day
- Scan once with a stack of days still waiting for a warmer day, popping them when one arrives
- Divide and conquer on the two halves of the array
Show the answer
C. Scan once with a stack of days still waiting for a warmer day, popping them when one arrives
This is next greater element with indices: every day is pushed once and popped at most once, so the scan is in total even though one day can pop many. The forward scan is on a decreasing sequence, about steps.
Key takeaways
- An amortized bound limits the total cost of every sequence of operations; single operations may still be expensive, and no probability is involved.
- The aggregate method bounds the total directly: appends to a doubling array cost under writes, increments of a binary counter flip under bits, and a multipop stack does at most work.
- The accounting method stores credit on elements and the potential method stores it in a function of the state; both are valid when the stored amount never drops below where it started ().
- Amortized bounds promise nothing about one operation's latency, and they can break when an operation lets an adversary revisit expensive states (decrements, shrinking at half, persistence).
- Look for amortization wherever elements enter and leave once or pointers only move forward: monotonic stacks and queues, two pointers, KMP, resizing hash tables.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A data structure supports insert in amortized time. Which statement is guaranteed?
- Every single insert takes time
- Any sequence of inserts, starting from an empty structure, takes time in total
- Inserts take time on average over random inputs
- Inserts take expected time over the structure's random choices
Show the answer
B. Any sequence of inserts, starting from an empty structure, takes time in total
Amortized bounds are worst-case bounds on totals. A single insert may still cost , as a dynamic array's resize does, but no sequence of inserts can cost more than .
A dynamic array grows by 1000 slots whenever it is full. What is the total cost of appends, for large ?
Show the answer
C.
Resizes happen every 1000 appends and copy elements, about copies in all: , only with a small constant. Any additive growth policy is quadratic; a constant factor above 1 is what makes appends amortized .
In the potential method, why must hold for every ?
- So that the sum of the amortized costs is an upper bound on the sum of the actual costs
- So that every single operation has a nonnegative amortized cost
- So that the potential function is unique
- So that the actual costs are bounded by a constant
Show the answer
A. So that the sum of the amortized costs is an upper bound on the sum of the actual costs
The sum telescopes: . If the potential could end below where it started, the amortized costs would undercount the work actually done, and the bound would be false.
A -bit binary counter supports both increment and decrement. In the worst case, what do operations cost in bit flips?
- , by the same potential as for increments
Show the answer
C.
Alternating between (a 0 followed by ones) and (a 1 followed by zeros) flips all bits every time. With increments only, each expensive operation lowers the number of 1 bits, and that is what the potential relied on; a decrement undoes that progress.
In the monotonic-stack algorithm for next greater elements on values, what is the largest possible total number of pops, over the whole run?
Show the answer
A.
Every index is pushed once and popped at most once, and the index of the largest value is never popped. An increasing sequence achieves : each new value pops the previous one. Together with the pushes, the stack does fewer than operations.
Go deeper
- The Potential Method in Depth · Designing potential functions: binary counters, growing and shrinking tables, and more.
- Online Algorithms & Competitive Analysis · Ski rental, paging and move-to-front: deciding without knowing the future.
- Deamortization & Global Rebuilding · Turning amortized bounds into worst-case ones.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 16, "Amortized Analysis".
- R. E. Tarjan, "Amortized computational complexity," SIAM Journal on Algebraic and Discrete Methods 6(2) (1985), 306–318.
- K. Mehlhorn & P. Sanders, Algorithms and Data Structures: The Basic Toolbox (Springer, 2008), chapter 3.