Sub topic 4
Accounting method: charging each append a fixed price
This chapter assumes you know Big-O notation and the doubling dynamic array from earlier in the tutorial. It also assumes you can read short Python programs. You should be able to state the aggregate-method result: n appends cost less than 3n units in total.
From totals to a price per operation
The aggregate method gives one number for the whole sequence and divides by n. It never says which operation pays for what. The accounting method (also called the banker's method) assigns each operation an explicit price and tracks who covers the expensive steps.
The setup has four parts:
- Every operation has an actual cost, such as one unit per element written or copied.
- You choose an amortised charge for each type of operation. This is the price the caller "pays".
- If the charge is higher than the actual cost, the surplus goes into a bank of credit. If the charge is lower, the operation withdraws credit to cover the gap.
- The bank balance must never go negative, at any point in the sequence.
If the balance stays at or above zero, then after any k operations the total amount charged is at least the total actual cost. Total actual cost is therefore bounded by the sum of the charges. If each append is charged a constant, the amortised cost per append is that constant.
The word "credit" is a bookkeeping device. Nothing in the program stores it. It is an argument about where the cost of a future resize has already been paid for.
The cost model
This chapter uses the same cost model as the aggregate method:
- Writing one element into a free slot costs 1.
- Copying one element during a resize costs 1.
- Allocating the new array is free, so only copies count.
A doubling array starts with capacity 1. When an append finds the array full, it allocates twice the capacity, copies every element, and then writes the new one.
Charging 3 per append
Charge every append a flat 3 units. Spend them like this:
- 1 unit pays for writing the new element.
- 2 units are stored as credit on that new element.
Now look at a resize. Suppose the array has capacity c and is full, and the next append triggers a doubling. The previous resize moved the array from capacity c/2 to c. After that resize, the array held c/2 elements, and those carried no credit, because the resize spent it. Since then, c/2 appends have filled the array to size c. Each of those appends left 2 units of credit, so the bank holds 2 × c/2 = c units.
The resize must copy c elements, which costs c. The stored credit covers it exactly. The balance returns to zero, and the append that triggered the resize pays its own write with 1 unit and deposits 2 for the next phase.
The idea is that the newest half of the array pays to copy the whole array. Each new element pays once for itself and once for one older element.
Checking the argument by running it
An accounting proof is only as good as its invariant, so test it. The program below simulates the bank for any charge. It tracks the lowest balance seen, including the moment inside a resize, after the copies are paid and before the write.
def simulate(n, charge):
"""Run n appends on a doubling array with a flat per-append charge.
Returns (final_bank, lowest_bank, actual_cost).
"""
capacity, size = 1, 0
bank, lowest, actual = 0, 0, 0
for _ in range(n):
bank += charge # the caller pays the flat price
if size == capacity:
bank -= size # withdraw one unit per copied element
actual += size
lowest = min(lowest, bank)
capacity *= 2
bank -= 1 # pay for writing the new element
actual += 1
size += 1
lowest = min(lowest, bank)
return bank, lowest, actual
for n in (10, 100, 1000, 10000):
bank, lowest, actual = simulate(n, 3)
assert lowest >= 0 # the invariant holds at every step
assert actual <= 3 * n # actual cost is bounded by total charges
assert bank == 3 * n - actual # bank = charged minus spent
print(f"charge 3, n={n}: actual={actual}, bank={bank}, lowest={lowest}")
bank, lowest, actual = simulate(10, 2)
print(f"charge 2, n=10: lowest bank = {lowest}")With a charge of 3 the lowest balance is never negative, and the bank at the end equals total charged minus total actual cost. With a charge of 2 the balance goes negative: the program prints a lowest balance of -1 for n = 10, so the charge is too small. At the fifth append the array copies 4 elements, but the bank only holds 3 units at that point. A charge of 2 pays for the write and one unit of credit, and one credit per element is not enough to cover copying both the new element and an old one.
The price of 3 is the cheapest flat price that works for doubling. The aggregate method gave a bound below 3n, and the accounting method reaches the same constant by a different route.
Why the bank must never go negative
The invariant is a statement about every prefix of the sequence, not just the end. A common mistake is to show that total charges exceed total cost for the full run of n appends. That is not enough, because the sequence might stop in the middle. If the bank is negative after k operations, the amortised charges for those k operations underpay the actual cost, and the bound fails for that prefix.
For the same reason, you cannot charge a price that only works "on average later". Credit has to exist before it is spent.
Where the credit lives
Many textbooks attach credit to individual elements, as the "newest half pays for the array" argument above does. This makes the argument local: each element carries 2 units, and a resize consumes them. It is a useful habit for two reasons:
- It shows you which operations create credit and which consume it, so you can check that nothing is spent twice.
- It extends naturally to data structures with many parts, such as stacks with multipop, where each stack item carries the credit for its own eventual removal.
You are free to treat the bank as one global number instead. The simulation above does exactly that. The per-element view is the more convincing proof, and the global number is the easier check in code.
Other growth factors
The same method works for a growth factor g greater than 1. Suppose the array of capacity c fills up and is resized to g·c. The previous phase added about c(1 − 1/g) elements, because it started with c/g elements after the previous resize. Those appends must together deposit enough credit to copy all c elements. Each append must therefore deposit
c / (c(1 − 1/g)) = g / (g − 1)
units. The flat charge is 1 for the write plus that deposit:
| Growth factor g | Deposit per append | Flat charge |
|---|---|---|
| 2 | 2 | 3 |
| 1.5 | 3 | 4 |
| 4 | 4/3 | 7/3 (about 2.33) |
The formula ignores rounding to whole slots, so treat the small-n behaviour as approximate. The pattern is useful: a smaller growth factor needs a larger flat price, because resizes are more frequent. A larger factor needs a smaller price but wastes more unused capacity. The trade-off between time and memory is covered in the chapter on growth strategy.
The method fails when growth is additive
Try to apply the argument to an array that grows by a fixed 16 slots. A resize at size m copies m elements, but only the 16 appends since the last resize have deposited credit. To cover m copies you would need to deposit m/16 per append, which grows with m. No fixed charge keeps the balance non-negative, so the accounting method cannot prove an O(1) bound, and the actual cost really is not O(1) amortised. The failure of the invariant is the same fact the aggregate method shows with totals.
What the accounting method does not tell you
- It does not say that any single append is cheap. One append still copies the whole array. The method bounds the average over every sequence, and it holds even for an adversarial sequence.
- It does not give an exact running time. The amortised charge is an upper bound on the actual cost, so the bank can hold unspent credit at the end.
- It does not depend on the input values. This is the key difference from average-case analysis, which needs assumptions about the distribution of inputs.
The method also leaves one limitation, which the next chapter addresses. You have to invent the credit placement and the charge yourself. For structures with many interacting operations, such as growing and shrinking arrays, that guessing becomes error-prone. The potential method replaces it with a single formula for the stored credit.
Exercise
A doubling array starts at capacity 1 and is charged 3 per append. After 8 appends, how many units are in the bank, and why? Use the cost model from this chapter (write = 1, copy = 1 per element).
Show answer
The charges total 3 × 8 = 24. The writes cost 8. The resizes happen on appends 2, 3, and 5, copying 1, 2, and 4 elements, which is 7 units. Actual cost is 8 + 7 = 15, so the bank holds 24 − 15 = 9 units. Check against the structure: the array has capacity 8 and is full, with elements 5 to 8 carrying 2 credits each (8 units) plus 1 unit of leftover credit from the earlier phases.
Exercise
Suppose the array grows by a factor of 3 instead of 2. Using the formula in this chapter, what flat charge per append keeps the bank non-negative, and what does each append deposit?
Show answer
The deposit is g / (g − 1) = 3 / 2 = 1.5 units per append. The flat charge is 1 for the write plus 1.5 for the deposit, so 2.5 units. Check: a phase starts at c/3 elements and adds 2c/3 appends. Those deposit 2c/3 × 1.5 = c units, which exactly pays for copying c elements.
Exercise
An array grows by adding 16 slots each time. A student says a flat charge of 100 per append is enough to cover every resize. Why is the student wrong, using the bank argument?
Show answer
A resize at size m copies m elements, but only the last 16 appends have deposited credit. Each deposits at most 99 units, so the bank holds at most 16 × 99 = 1584 units. Once m exceeds that, the resize needs more than the bank holds and the balance goes negative. Any fixed charge has the same limit, so no constant charge works.