Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

The Potential Method in Depth

Designing potential functions: binary counters, growing and shrinking tables, and more.

A good potential function is a measure of disorder: it is high exactly when an expensive operation is coming and falls when that operation happens. Finding one is an art, and the hardest analyses in data structures, splay trees, Fibonacci heaps and union–find, are triumphs of choosing Φ\Phi. This lesson builds the skill on three problems where the obvious structure fails and a well-chosen potential proves the fix.

What you’ll learn

  • State the potential-method theorem precisely, and relate potentials to the accounting method.
  • Prove that a table that doubles when full and halves when a quarter full has O(1)O(1) amortized cost per operation, and show that halving at one half thrashes.
  • Make a counter with increments and decrements run in O(1)O(1) amortized time with a redundant number representation.
  • Analyze skew heaps with the heavy-node potential: O(log⁡n)O(\log n) amortized meld, although a single operation can cost Θ(n)\Theta(n).

The framework, and how to design a potential

The potential method and the accounting method are two views of one idea; Tarjan's survey (1985) calls them the physicist's and the banker's view. Credits stored on elements add up to a potential, and conversely any valid assignment of amortized costs defines a potential: let Φ(Di)\Phi(D_i) be the total of c^j−cj\hat c_j-c_j over the first ii operations. The physicist's view wins when the credit is a global quantity that no single element owns.

How to find a good Φ\Phi? Ask what makes an operation expensive, and make Φ\Phi measure exactly that, with a coefficient large enough to pay for it:

  • a dynamic array is expensive when it is full: Φ\Phi grows as the array fills;
  • a binary counter is expensive when it ends in many 1s: Φ\Phi counts 1s;
  • a move-to-front list is expensive when it disagrees with a better list: Φ\Phi counts the disagreements (in Online Algorithms & Competitive Analysis);
  • a splay tree is expensive when it is deep and unbalanced: Φ=∑xlog⁡2(size of x’s subtree)\Phi=\sum_x\log_2(\text{size of }x\text{'s subtree}).

Tables that grow and shrink

A dynamic table should also give memory back when elements are removed. The natural rule, halve the capacity when the table becomes half full, is a trap. Fill a table of capacity cc completely and append once: it doubles to 2c2c and copies cc elements. Pop once: now it is exactly half full, so it halves and copies cc elements. Append again: full, so it doubles. Alternating appends and pops makes every operation cost Θ(c)\Theta(c), so nn operations cost Θ(n2)\Theta(n^2).

The fix leaves room between the two thresholds: double when full, but halve only when fewer than a quarter of the slots are used. After any resize the table is about half full, and Θ(capacity)\Theta(\text{capacity}) operations must pass before the next one.

Predict before you look

A table has just doubled from capacity 64 to 128 and holds 65 elements. It halves when, after a pop, fewer than a quarter of its slots are used. How many pops in a row does it take to trigger the next halving?

Show the answer

34

Fewer than 128/4=32128/4=32 elements means at most 31, so it takes 65−31=3465-31=34 pops. In the other direction, 63 appends would fill it. Either way, about half the capacity's worth of operations separates two resizes, which is what lets each resize be paid for.

DerivationEvery operation has amortized cost at most 3
  1. c^=1+2=3c^=(c+1)+(2−c)=3\hat c=1+2=3\qquad\qquad\hat c=(c+1)+(2-c)=3

    Append, no resize, α≥12\alpha\ge\frac12 before and after: cost 1, Φ\Phi rises by 2. Append that doubles a full table of capacity cc: cost c+1c+1, and Φ\Phi falls from cc to 2(c+1)−2c=22(c+1)-2c=2:

  2. c^=1−1=0\hat c=1-1=0

    Append while α<12\alpha<\frac12: cost 1 and Φ=c/2−s\Phi=c/2-s falls by 1; if the append reaches exactly half full, Φ\Phi goes from 1 to 0. Either way:

  3. c^∈{1−2, 1+1, 1+1}⟹c^≤2\hat c\in\{1-2,\ 1+1,\ 1+1\}\quad\Longrightarrow\quad\hat c\le2

    Pop, no resize: cost 1. With α≥12\alpha\ge\frac12 before and after, Φ\Phi falls by 2; crossing below one half moves Φ\Phi from 0 to 1; below one half, Φ\Phi rises by 1:

  4. c^=c4+(1−c4)=1\hat c=\frac c4+\Big(1-\frac c4\Big)=1

    Pop that halves: the pop leaves s=c/4−1s=c/4-1 elements, which are copied into capacity c/2c/2. Cost 1+s=c/41+s=c/4, while Φ\Phi falls from c/2−c/4=c/4c/2-c/4=c/4 to c/4−(c/4−1)=1c/4-(c/4-1)=1:

Φ\Phi starts at 0 and is never negative, so any nn appends and pops from an empty table cost at most 3n3n element writes. A simulation of random and adversarial sequences confirms the case analysis: appends never exceed amortized cost 3 and pops never exceed 2.

Counters that count both ways

With increments only, the number of 1 bits pays for every carry. Add decrements and the potential fails: alternating between 0111⋯10111\cdots1 and 1000⋯01000\cdots0 flips all kk bits each time. The problem is the representation, which has one expensive state on each side of every boundary.

The fix is redundancy. Let each digit did_i be 0, 1 or 2, still with weight 2i2^i, so a number has several representations. An increment adds 1 to d0d_0; a digit that would become 3 is set to 1 and carries, because 2+1=3=1+22+1=3=1+2. A decrement subtracts 1 from d0d_0; a digit that would become −1-1 is set to 1 and borrows, because 0−1=−1=1−20-1=-1=1-2. In both directions a long chain leaves behind a run of 1s, the safest digit, one step away from both ends.

DerivationProof
  1. c^ ≤ (t+1)−t+1 = 2\hat c\ \le\ (t+1)-t+1\ =\ 2

    Increment. A carry chain of length tt turns tt digits 2 into 1, lowering Φ\Phi by tt. The last digit touched goes from 0 to 1 (lowering Φ\Phi by 1), or from 1 to 2 (raising it by 1), or is a new leading 1 (no change). With actual cost t+1t+1:

  2. c^ ≤ (t+1)−t+1 = 2\hat c\ \le\ (t+1)-t+1\ =\ 2

    Decrement. A borrow chain of length tt turns tt digits 0 into 1, lowering Φ\Phi by tt. The last digit goes from 2 to 1 (lowering Φ\Phi), or from 1 to 0 (raising it by 1), or is a leading 1 that disappears (no change):

  3. ∑i=1mci ≤ ∑i=1mc^i ≤ 2m\sum_{i=1}^{m}c_i\ \le\ \sum_{i=1}^{m}\hat c_i\ \le\ 2m

    Φ\Phi starts at 0 and is never negative, so the potential-method theorem applies:

A simulation of 300,000 random increments and decrements confirms it: no operation ever had amortized cost above 2. Redundant representations reappear in worst-case structures: skew binary numbers, with digits 0, 1, 2 and a rule that only the lowest nonzero digit may be 2, support both operations in O(1)O(1) worst-case time, and Deamortization & Global Rebuilding builds on that idea.

Skew heaps: a self-adjusting example

A skew heap (Sleator & Tarjan, 1986) is a heap-ordered binary tree with no balance information at all. Its one operation is meld: walk down the right spines of both heaps, merging them in key order, and then swap the two children of every node on that merge path. Insert is a meld with a one-node heap, and delete-min melds the root's two subtrees.

python
class Node:
    def __init__(self, key):
        self.key, self.left, self.right = key, None, None

def meld(a, b):
    """Merge two skew heaps (min-heaps) and return the new root."""
    if a is None: return b
    if b is None: return a
    if b.key < a.key:
        a, b = b, a                       # a holds the smaller root
    a.right = meld(a.right, b)            # merge along the right spine
    a.left, a.right = a.right, a.left     # then swap a's children
    return a

Recursive for clarity; its depth is the length of the merge path, which, as we will see, can be linear.

DerivationAmortized cost of meld: at most log₂ n₁ + log₂ n₂ + log₂ n
  1. ℓ ≤ log⁡2n1+log⁡2n2\ell\ \le\ \log_2n_1+\log_2n_2

    Let the merge path have ℓ\ell light and hh heavy nodes, taken from the right spines of heaps of sizes n1n_1 and n2n_2. The actual cost is ℓ+h\ell+h, and the light ones are few:

  2. ΔΦ ≤ (newly heavy nodes)−h\Delta\Phi\ \le\ (\text{newly heavy nodes})-h

    Heavy nodes become light. A heavy node xx on the path keeps its old left subtree, now as its right child, while its old right subtree, only bigger after the merge, becomes its left child. So xx ends up light. Nodes off the path keep their subtrees and their status.

  3. c^ ≤ (ℓ+h)+log⁡2n−h ≤ log⁡2n1+log⁡2n2+log⁡2n ≤ 3log⁡2n\hat c\ \le\ (\ell+h)+\log_2n-h\ \le\ \log_2n_1+\log_2n_2+\log_2n\ \le\ 3\log_2n

    Newly heavy nodes are few. After the swaps, the merge path is the leftmost path of the new heap, which has n=n1+n2n=n_1+n_2 nodes, so at most log⁡2n\log_2n of its nodes are heavy:

So insert, delete-min and meld all take O(log⁡n)O(\log n) amortized time, and a simulation finds no meld whose amortized cost exceeds log⁡2n1+log⁡2n2+log⁡2n\log_2n_1+\log_2n_2+\log_2n. The constant is not tight: Kaldewaij and Schoenmakers (1991) proved log⁡φn≈1.44log⁡2n\log_\varphi n\approx1.44\log_2n amortized comparisons per meld, and Schoenmakers (1997) showed that bound is attained.

Think first The bound is amortized. Can a single skew-heap insert really take linear time?

Yes. Start from one node and repeat: insert a new minimum, which makes the whole old heap its left child, then insert a key larger than that minimum, which swaps the old heap onto the right. Each round lengthens the right spine by one. After 4000 such inserts the heap has 4001 nodes and a right spine of 2001; inserting one more large key walks the entire spine, 2001 merge steps. The potential paid for it: the spine was made of heavy nodes.

Where potentials lead

The same craft proves the landmark bounds of data structures. Splay trees (Sleator & Tarjan, 1985) use Φ=∑xlog⁡2s(x)\Phi=\sum_x\log_2 s(x), where s(x)s(x) is the size of xx's subtree, and the access lemma gives O(log⁡n)O(\log n) amortized time per operation, with no balance information stored. Fibonacci heaps (Fredman & Tarjan, 1987) use the number of trees plus twice the number of marked nodes to get O(1)O(1) amortized decrease-key. Union–find with path compression and union by rank reaches O(α(n))O(\alpha(n)) amortized per operation, the inverse Ackermann function, through an elaborate potential.

Key takeaways

  • The potential method: c^i=ci+Φ(Di)−Φ(Di−1)\hat c_i=c_i+\Phi(D_i)-\Phi(D_{i-1}), and ∑ci≤∑c^i\sum c_i\le\sum\hat c_i whenever Φ\Phi never drops below its initial value. Credits and potentials are two views of the same bookkeeping.
  • Design Φ\Phi to measure what makes the next operation expensive. For a table that doubles when full and halves when a quarter full, Φ=2s−c\Phi=2s-c or c/2−sc/2-s gives amortized cost at most 3; halving at one half thrashes at Θ(n)\Theta(n) per operation.
  • A redundant representation, digits 0, 1, 2 with Φ=\Phi= the number of digits other than 1, gives increments and decrements O(1)O(1) amortized cost, where plain binary costs Θ(k)\Theta(k).
  • Skew heaps meld in O(log⁡n)O(\log n) amortized time with the heavy-node potential, although single operations can be linear; splay trees, Fibonacci heaps and union–find rest on the same method, and dynamic optimality remains open.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A table doubles when full and halves as soon as it is half full. What is the worst-case total cost of nn appends and pops?

  1. O(n)O(n)
  2. O(nlog⁡n)O(n\log n)
  3. Θ(n2)\Theta(n^2)
  4. O(n)O(n) in expectation
Show the answer

C. Θ(n2)\Theta(n^2)

Right after a doubling, one pop makes the table half full and halves it, and one append doubles it again: each operation copies about half the table. Halving at a quarter leaves a gap of Θ(capacity)\Theta(\text{capacity}) operations between resizes, which restores O(1)O(1) amortized cost.

Question 2

In the counter with digits 0, 1, 2 and Φ=\Phi= the number of digits that are not 1, why does a long carry chain have small amortized cost?

  1. Because carries never happen with digits up to 2
  2. Because each carry turns a 2 into a 1, and each such step lowers Φ\Phi by 1, paying for itself
  3. Because the representation is unique, so the counter cannot oscillate
  4. Because a decrement always undoes the previous increment's carries
Show the answer

B. Because each carry turns a 2 into a 1, and each such step lowers Φ\Phi by 1, paying for itself

A chain of tt carries costs t+1t+1 and lowers Φ\Phi by at least t−1t-1; symmetric borrows turn 0s into 1s. Either way the chain leaves 1s behind, which are cheap for both an increment and a decrement, so an adversary cannot make the next operation expensive again without first paying to raise Φ\Phi.

Question 3

Which statement about skew heaps is true?

  1. Every meld takes O(log⁡n)O(\log n) time in the worst case
  2. They store a rank or a height in every node to stay balanced
  3. Every sequence of mm operations takes O(mlog⁡n)O(m\log n) time, though a single meld can take Θ(n)\Theta(n)
  4. Their melds take O(1)O(1) amortized time
Show the answer

C. Every sequence of mm operations takes O(mlog⁡n)O(m\log n) time, though a single meld can take Θ(n)\Theta(n)

The heavy-node potential bounds each meld by log⁡2n1+log⁡2n2+log⁡2n\log_2n_1+\log_2n_2+\log_2n amortized. A single meld can still walk a right spine of linear length, which a sequence of inserts can build; the potential stored in its heavy nodes pays for that walk.

Question 4

An accounting scheme stores credit on elements and never lets the total credit go negative. How do you turn it into a potential function?

  1. Let Φ\Phi be the total credit currently stored in the structure
  2. Let Φ\Phi be the number of operations performed so far
  3. It cannot be done: some accounting arguments have no potential
  4. Let Φ\Phi be the largest credit on any single element
Show the answer

A. Let Φ\Phi be the total credit currently stored in the structure

With Φ\Phi the stored credit, c^i=ci+ΔΦ\hat c_i=c_i+\Delta\Phi is exactly the charge of the operation, Φ\Phi starts at 0 and never goes negative. The two methods are the banker's and the physicist's view of the same idea.

Further reading

  • R. E. Tarjan, "Amortized computational complexity," SIAM Journal on Algebraic and Discrete Methods 6(2) (1985), 306–318.
  • D. D. Sleator & R. E. Tarjan, "Self-adjusting heaps," SIAM Journal on Computing 15(1) (1986), 52–69.
  • A. Kaldewaij & B. Schoenmakers, "The derivation of a tighter bound for top-down skew heaps," Information Processing Letters 37(5) (1991), 265–271.
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 16.