TExcelTAD

The Accounting Method

The aggregate method added up the cost of a whole sequence. The accounting method works one operation at a time, like a budget. Each operation is charged a fixed price, its amortized cost, which may be more or less than what it actually costs. When an operation is overcharged, the surplus is stored as credit on specific objects of the data structure; later, an expensive operation pays for its extra work with that stored credit. If the credit never runs out, the total of the prices bounds the total actual cost. The method lets different operations have different amortized costs, and the credit gives a concrete picture of why the bound holds.

The rule

Let operation ii have actual cost cic_i and amortized cost c^i\hat{c}_i. The prices are valid if, for every sequence and every prefix of it,

∑i=1mc^i ≥ ∑i=1mcifor all m,\sum_{i=1}^{m} \hat{c}_i \ \ge\ \sum_{i=1}^{m} c_i \quad \text{for all } m,

that is, the stored credit ∑i≤m(c^i−ci)\sum_{i \le m} (\hat{c}_i - c_i) is never negative. Then the total amortized cost is an upper bound on the total actual cost of the sequence. The condition must hold for every prefix, not just at the end: a scheme that goes into debt in the middle could be hiding a sequence that stops right there.

In practice, one shows the stronger, local statement that every unit of credit sits on some object, and every expensive operation finds enough credit on the objects it touches.

The stack with multipop

Charge the operations:

operation actual cost amortized cost
PUSH 1 2
POP 1 0
MULTIPOP(k) min⁡(k,s)\min(k, s) 0

Why the credit never runs out. A push pays 1 for itself and leaves 1 unit of credit on the object it pushed. Every object in the stack therefore carries one unit. A pop, whether alone or inside a multipop, removes an object and uses that object's credit to pay for its removal. So the credit is exactly the number of objects on the stack, which is never negative. The total actual cost of nn operations is at most the total amortized cost, at most 2n2n.

python · try it yourself
import random

def simulate(ops):
    stack, credit, low = [], 0, 0
    total_actual = total_amortized = 0
    for op, k in ops:
        if op == "push":
            stack.append(1); actual, amortized = 1, 2
        elif op == "pop":
            actual = 1 if stack else 0
            if stack: stack.pop()
            amortized = 0
        else:
            actual = min(k, len(stack)); del stack[len(stack) - actual:]; amortized = 0
        credit += amortized - actual
        low = min(low, credit)
        assert credit == len(stack)                # one unit of credit per stored object
        total_actual += actual; total_amortized += amortized
    return total_actual, total_amortized, low

rng = random.Random(9)
ops = [("push", 0) if rng.random() < 0.55 else ("multipop", rng.randint(1, 6)) for _ in range(20)]
stack, credit = 0, 0
for op, k in ops[:10]:
    cost = 1 if op == "push" else min(k, stack)
    stack += 1 if op == "push" else -cost
    credit += (2 if op == "push" else 0) - cost
    print(f"{op:8}{'' if op == 'push' else ' ' + str(k):3}  actual {cost}  stack size {stack}  credit {credit}")

ops = [("push", 0) if rng.random() < 0.6 else ("multipop", rng.randint(1, 50)) for _ in range(100000)]
actual, amortized, low = simulate(ops)
print(f"100000 operations: actual {actual}, amortized {amortized}, lowest credit {low}")
push         actual 1  stack size 1  credit 1
push         actual 1  stack size 2  credit 2
push         actual 1  stack size 3  credit 3
multipop 1   actual 1  stack size 2  credit 2
push         actual 1  stack size 3  credit 3
push         actual 1  stack size 4  credit 4
multipop 3   actual 3  stack size 1  credit 1
multipop 5   actual 1  stack size 0  credit 0
multipop 6   actual 0  stack size 0  credit 0
push         actual 1  stack size 1  credit 1
100000 operations: actual 119934, amortized 119934, lowest credit 0

Every line shows credit equal to the stack size, and over 100,000 operations the credit never dips below zero. In general the amortized total overestimates the actual total by exactly the credit still sitting on the objects at the end; in the long run here the stack happens to end empty, so the two totals agree. (The C++ run below ends with two objects on the stack, and its totals differ by 2.)

The binary counter

Charge 2 for setting a bit from 0 to 1, and 0 for resetting a bit from 1 to 0. Setting pays 1 for the flip itself and leaves 1 unit of credit on that bit. Every 1 bit of the counter therefore carries one unit of credit, and when an increment resets trailing ones to zero, each of them pays for its own reset with its credit.

An increment resets some number tt of bits (amortized cost 0) and sets at most one bit (amortized cost 2). So its amortized cost is at most 2, and nn increments from zero cost at most 2n2n. The credit equals the number of 1 bits, never negative.

python · try it yourself
def increment(A):
    resets, i = 0, 0
    while i < len(A) and A[i] == 1:
        A[i] = 0; resets += 1; i += 1
    sets = 0
    if i < len(A):
        A[i] = 1; sets = 1
    return resets, sets

A, credit = [0] * 6, 0
for n in range(1, 13):
    resets, sets = increment(A)
    actual, amortized = resets + sets, 2 * sets
    credit += amortized - actual
    print(f"{n:2}: {''.join(map(str, reversed(A)))}  actual {actual}  amortized {amortized}  credit {credit}  ones {sum(A)}")
 1: 000001  actual 1  amortized 2  credit 1  ones 1
 2: 000010  actual 2  amortized 2  credit 1  ones 1
 3: 000011  actual 1  amortized 2  credit 2  ones 2
 4: 000100  actual 3  amortized 2  credit 1  ones 1
 5: 000101  actual 1  amortized 2  credit 2  ones 2
 6: 000110  actual 2  amortized 2  credit 2  ones 2
 7: 000111  actual 1  amortized 2  credit 3  ones 3
 8: 001000  actual 4  amortized 2  credit 1  ones 1
 9: 001001  actual 1  amortized 2  credit 2  ones 2
10: 001010  actual 2  amortized 2  credit 2  ones 2
11: 001011  actual 1  amortized 2  credit 3  ones 3
12: 001100  actual 3  amortized 2  credit 2  ones 2

The credit column equals the number of ones after every step. At n=8n = 8 the increment flips four bits but is charged only 2: three of the four flips were paid long ago, when those bits were set.

A useful consequence: starting from an arbitrary counter value with b0b_0 ones, nn increments cost at most 2n+b02n + b_0, because the initial ones must be "pre-funded" with b0b_0 units of credit. The accounting view makes such starting conditions easy to state. The potential method makes them precise.

In C++

The stack scheme in C++, with the credit kept explicitly as a counter on each stored object (here, simply an int stored with the element) to show the local bookkeeping.

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

struct Entry { int value; int credit; };

int main() {
    std::vector<Entry> stack;
    std::mt19937 rng(5);
    long long actual = 0, amortized = 0;
    bool always_paid = true;
    for (int op = 0; op < 200000; ++op) {
        if (rng() % 10 < 6) {                      // PUSH: charge 2, keep 1 on the object
            stack.push_back({op, 1});
            actual += 1; amortized += 2;
        } else {                                   // MULTIPOP(k): charge 0, paid by the objects' credit
            int k = 1 + static_cast<int>(rng() % 40);
            while (k-- > 0 && !stack.empty()) {
                if (stack.back().credit != 1) always_paid = false;
                stack.pop_back();
                actual += 1;
            }
        }
    }
    std::printf("actual %lld, amortized %lld, every pop paid by stored credit: %s\n",
                actual, amortized, always_paid ? "yes" : "no");
}
actual 241102, amortized 241104, every pop paid by stored credit: yes

Choosing the prices

The amortized costs are a design decision, and there are two ways to get them wrong.

  • Too low: the credit eventually goes negative for some sequence. Charging 1 for a push and 0 for a pop gives a total that is less than the actual cost of "push, pop", so it is invalid.
  • Too high: valid but useless. Charging nn per operation is a correct accounting scheme and a worthless bound.

The art is to find the smallest prices for which a credit invariant ("every object holds one unit", "every 1 bit holds one unit") can be proved. The invariant is what makes the proof local: each operation checks only the objects it touches.

Test yourself

In the accounting method, what must be true for the amortized costs to give a valid bound?

  1. Each amortized cost is at least the actual cost of that operation
  2. The total amortized cost of every prefix of every sequence is at least its total actual cost
  3. The amortized costs are all equal
  4. The credit is zero at the end

In the binary-counter scheme, where is the credit stored?

  1. On every 0 bit
  2. On every 1 bit, one unit each
  3. On the most significant bit
  4. In a global account only

A stack starts empty. After the operations PUSH, PUSH, PUSH, MULTIPOP(2), PUSH, how much credit is stored under the scheme PUSH = 2, POP = MULTIPOP = 0?

  1. 0
  2. 1
  3. 2
  4. 4