TExcelTAD

The Potential Method

The accounting method stored credit on individual objects. The potential method keeps the same idea but stores the credit as a function of the whole data structure, like potential energy in physics: work done now can raise the potential, and later operations can release it. One function Φ\Phi replaces all the bookkeeping, the amortized costs follow from it by a formula, and the proof that the bound is valid reduces to one inequality. It is the most flexible of the three methods, and the one used for advanced structures such as splay trees, Fibonacci heaps and union-find.

The definitions

Start with a data structure D0D_0 and perform nn operations; let cic_i be the actual cost of operation ii and DiD_i the structure after it. A potential function Φ\Phi maps each state DD to a real number Φ(D)\Phi(D). The amortized cost of operation ii is defined as

c^i=ci+Φ(Di)−Φ(Di−1),\hat{c}_i = c_i + \Phi(D_i) - \Phi(D_{i-1}),

the actual cost plus the change in potential. Summing over the sequence, the potential differences telescope:

∑i=1nc^i=∑i=1nci+Φ(Dn)−Φ(D0).\sum_{i=1}^{n} \hat{c}_i = \sum_{i=1}^{n} c_i + \Phi(D_n) - \Phi(D_0).

So if Φ(Dn)≥Φ(D0)\Phi(D_n) \ge \Phi(D_0) for every nn, the total amortized cost bounds the total actual cost. The usual way to guarantee this is to define Φ(D0)=0\Phi(D_0) = 0 and show Φ(D)≥0\Phi(D) \ge 0 for every reachable state DD.

An operation whose amortized cost exceeds its actual cost raises the potential (it "stores energy"); an expensive operation can have a small amortized cost if it releases a lot of potential. The job is to choose Φ\Phi so that every operation's amortized cost comes out small.

The stack with multipop

Let Φ(S)\Phi(S) be the number of objects on the stack. It starts at 0 and is never negative.

  • PUSH: c=1c = 1, potential rises by 1, so c^=1+1=2\hat{c} = 1 + 1 = 2.
  • POP: c=1c = 1, potential falls by 1, so c^=1−1=0\hat{c} = 1 - 1 = 0.
  • MULTIPOP(k) popping k′=min⁡(k,s)k' = \min(k, s) objects: c=k′c = k', potential falls by k′k', so c^=k′−k′=0\hat{c} = k' - k' = 0.

Every operation has amortized cost at most 2, so nn operations cost at most 2n2n: the same numbers as the accounting scheme, because the potential is just the total credit stored on the objects.

The binary counter, from any starting value

Let Φ\Phi be bb, the number of 1 bits in the counter. Suppose increment ii resets tit_i bits. Its actual cost is at most ti+1t_i + 1 (the resets plus at most one set), and the number of ones changes from bi−1b_{i-1} to at most bi−1−ti+1b_{i-1} - t_i + 1. So

c^i≤(ti+1)+(bi−1−ti+1)−bi−1=2.\hat{c}_i \le (t_i + 1) + (b_{i-1} - t_i + 1) - b_{i-1} = 2.

(When the counter overflows, all kk bits are reset and none is set, and c^i=k−k=0\hat{c}_i = k - k = 0.)

If the counter starts at 0, Φ(D0)=0≤Φ(Dn)\Phi(D_0) = 0 \le \Phi(D_n), and nn increments cost at most 2n2n. The potential method also handles a counter that starts with b0b_0 ones: the telescoped sum gives

∑i=1nci=∑i=1nc^i−bn+b0≤2n−bn+b0,\sum_{i=1}^{n} c_i = \sum_{i=1}^{n} \hat{c}_i - b_n + b_0 \le 2n - b_n + b_0 ,

so as long as n=Ω(k)n = \Omega(k), the total is still O(n)O(n): the potential stored in the initial ones is at most kk, which is absorbed by the 2n2n.

python · try it yourself
import random

def increment(A):
    i, c = 0, 0
    while i < len(A) and A[i] == 1:
        A[i] = 0; c += 1; i += 1
    if i < len(A):
        A[i] = 1; c += 1
    return c

k = 16
rng = random.Random(4)
A = [rng.randint(0, 1) for _ in range(k)]                  # an arbitrary starting value
b0 = sum(A)
print("start:", "".join(map(str, reversed(A))), " b0 =", b0)
total, worst_amortized = 0, 0
for n in range(1, 2001):
    before = sum(A)
    c = increment(A)
    amortized = c + sum(A) - before                           # c_i + Phi(D_i) - Phi(D_{i-1})
    worst_amortized = max(worst_amortized, amortized)
    total += c
print(f"2000 increments: actual total {total}, bound 2n - b_n + b0 = {2 * 2000 - sum(A) + b0}, "
      f"largest amortized cost {worst_amortized}")
start: 0110011000011010  b0 = 7
2000 increments: actual total 3997, bound 2n - b_n + b0 = 3997, largest amortized cost 2

The bound holds with equality: when no overflow happens, every increment has amortized cost exactly 2, so the telescoped sum is exact.

A queue from two stacks

A sharper example shows how the potential absorbs a "bulk transfer". Build a FIFO queue from two stacks: inbox receives new elements, outbox serves them. To dequeue, pop from outbox; if it is empty, first move every element of inbox to outbox (which reverses their order, putting the oldest on top). Each push or pop costs 1. A dequeue that triggers a transfer of tt elements costs 2t+12t + 1, which can be Θ(n)\Theta(n).

Take Φ=2⋅∣inbox∣\Phi = 2 \cdot \lvert \mathit{inbox} \rvert: every element in the inbox carries the cost of its future move.

  • ENQUEUE: c=1c = 1, ΔΦ=2\Delta\Phi = 2, so c^=3\hat{c} = 3.
  • DEQUEUE with a nonempty outbox: c=1c = 1, ΔΦ=0\Delta\Phi = 0, so c^=1\hat{c} = 1.
  • DEQUEUE that transfers tt elements: c=2t+1c = 2t + 1, ΔΦ=−2t\Delta\Phi = -2t, so c^=1\hat{c} = 1.

So any sequence of nn queue operations costs at most 3n3n, although single dequeues can be very slow.

python · try it yourself
import random

class TwoStackQueue:
    def __init__(self):
        self.inbox, self.outbox = [], []
    def phi(self):
        return 2 * len(self.inbox)
    def enqueue(self, x):
        self.inbox.append(x)
        return 1
    def dequeue(self):
        cost = 0
        if not self.outbox:
            while self.inbox:
                self.outbox.append(self.inbox.pop()); cost += 2
        self.outbox.pop()
        return cost + 1

rng = random.Random(10)
q, size = TwoStackQueue(), 0
amortized_seen, total, worst = set(), 0, 0
for _ in range(50000):
    before = q.phi()
    if size == 0 or rng.random() < 0.55:
        c, kind = q.enqueue(0), "enqueue"; size += 1
    else:
        c, kind = q.dequeue(), "dequeue"; size -= 1
    amortized_seen.add((kind, c + q.phi() - before))
    total += c
    worst = max(worst, c)
print("amortized costs observed:", sorted(amortized_seen))
print(f"50000 operations: actual total {total} <= 3n = {3 * 50000}; most expensive single operation {worst}")
amortized costs observed: [('dequeue', 1), ('enqueue', 3)]
50000 operations: actual total 101326 <= 3n = 150000; most expensive single operation 9773

Only two amortized values ever appear, 3 for an enqueue and 1 for a dequeue, exactly as derived, while some single dequeues cost thousands of steps.

In C++

The same queue with std::vector stacks, checking the amortized costs on every operation.

cpp · try it yourself
#include <cstdio>
#include <random>
#include <vector>

int main() {
    std::vector<int> inbox, outbox;
    std::mt19937 rng(10);
    long long total = 0;
    int worst = 0, size = 0;
    bool amortized_ok = true;
    for (int op = 0; op < 1000000; ++op) {
        long long phi_before = 2LL * inbox.size();
        int cost;
        bool enq = size == 0 || rng() % 100 < 55;
        if (enq) { inbox.push_back(op); cost = 1; ++size; }
        else {
            cost = 0;
            if (outbox.empty())
                while (!inbox.empty()) { outbox.push_back(inbox.back()); inbox.pop_back(); cost += 2; }
            outbox.pop_back(); cost += 1; --size;
        }
        long long amortized = cost + 2LL * inbox.size() - phi_before;
        if (amortized != (enq ? 3 : 1)) amortized_ok = false;
        total += cost;
        if (cost > worst) worst = cost;
    }
    std::printf("1000000 operations: total %lld <= 3000000, worst single op %d, amortized 3/1 every time: %s\n",
                total, worst, amortized_ok ? "yes" : "no");
}
1000000 operations: total 1904428 <= 3000000, worst single op 161179, amortized 3/1 every time: yes

How the three methods compare

method what you prove strengths
aggregate a bound T(n)T(n) on every sequence of nn operations simplest; one number for all operations
accounting prices per operation and a credit invariant on objects different costs per operation; concrete picture
potential a function Φ≥Φ(D0)\Phi \ge \Phi(D_0) of the state flexible, handles arbitrary starts; standard for complex structures

The accounting and potential methods are two views of the same thing: the potential is the total credit, and credit on objects is a way to define a potential. Choosing Φ\Phi is the creative step. A good first guess is "the amount of work the structure has been allowed to defer": unmoved inbox elements, ones that will have to be reset, and, in the next lesson, the elements a dynamic table will have to copy at its next expansion (Dynamic Tables: Expansion).

Test yourself

What condition makes the total amortized cost an upper bound on the total actual cost in the potential method?

  1. Φ(Di)≥0\Phi(D_i) \ge 0 for the final state only
  2. Φ(Dn)≥Φ(D0)\Phi(D_n) \ge \Phi(D_0) for every nn
  3. Φ\Phi is increasing
  4. Every amortized cost is at least the actual cost

With Φ\Phi = number of 1 bits, what is the amortized cost of an increment that changes 0101 11110101\,1111 into 0110 00000110\,0000?

  1. 1
  2. 2
  3. 5
  4. 6

In the two-stack queue with Φ=2∣inbox∣\Phi = 2\lvert\mathit{inbox}\rvert, a dequeue moves 10 elements. What are its actual and amortized costs?

  1. 21 and 1
  2. 21 and 21
  3. 11 and 1
  4. 20 and 0