★ Amortized analysis example: another binary counter [00TC]

Take the same binary counter incrementing example, but now suppose it costs 2^i to flip bit i. The worst case for a single increment operation is now \Theta (n), since if we have to flip all the bits it will cost 2^0 + 2^1 + 2^2 + \dots which is approximately equal to n. But once again, the total time to do n successive increment operations is actually less than \Theta (n^2). Let’s again make a table and look for patterns.

n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
incr 1 3 1 7 1 3 1 15 1 3 1 7 1 3 1 31
total 0 1 4 5 12 13 16 17 32 33 36 37 44 45 48 49 80

Looking at just the powers of 2 might reveal a useful pattern: 2 \to 4, 4 \to 12, 8 \to 32, 16 \to 80. It looks like each power of 2 is being multiplied by successive integers (2 \times 2, 4 \times 3, 8 \times 4, 16 \times 5…)in particular 2^k is being multiplied by k+1. So we conjecture that the total cost to increment from 0 to n is no greater than n \times (\lg n + 1), which would mean that the amortized cost of each increment operation is \Theta (\lg n).

To show this, we can use the accounting method: every time we do an increment, just put $1 on every bit, whether we flip it or not. (We have to decide up front how many bits we are going to use.) Since bit i is flipped every 2^i increment operations, by the time we flip it we will have accumulated exactly enough money to pay for its cost of 2^i. Therefore, the amortized cost of a single increment is the amount we actually pay: we pay $1 for each bit and there are \Theta (\lg n) bits.

We could also use the direct calculation method. Note that bit i is flipped only once every 2^i increments, and flipping it costs 2^i. So each bit contributes a total cost that is at most the total number of increment operations. There are \lg n + 1 bits, and each contributes a cost of at most n, for a total of at most n (\lg n + 1).