Approaching increment cost via a table [00T1]
The first step is almost always to just try small examples, play around, make a table, and notice patterns to come up with a guess. Let’s try it for incrementing a binary counter. We’ll make a table with the counter value n and the cumulative number of bit flips on the right-hand side. Remember we don’t need a formula for the number of bit flips (though it turns out in this case it is possible to come up with one!); we are just trying to figure out how fast it grows in relation to n.
| n | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| flips | 1 | 2 | 1 | 3 | 1 | 2 | 1 | 4 | 1 | 2 | 1 | 3 | 1 | 2 | 1 | 5 | |
| total | 0 | 1 | 3 | 4 | 7 | 8 | 10 | 11 | 15 | 16 | 18 | 19 | 22 | 23 | 25 | 26 | 31 |
We notice some patterns: whenever n is a power of two, the total number of bit flips seems to be one less than the next power of two. In fact, in general it seems that the cumulative number of bit flips is never more than 2n. That is, we conjecture that T(n) < 2n for all n > 0. Based on this evidence, we conjecture that a sequence of n increment operations starting from 0 actually takes \Theta (n), the lower bound we derived from the best case, rather than the worst-case upper bound of \Theta (n \lg n). Intuitively, it seems like the “expensive” increment operations happen infrequently enough that they don’t add too much to the total—we can “average out” their cost over the whole sequence.
The average cost of a single increment operation is just the total cost, T(n), divided by the number of operations (n). If it's true that T(n) < 2n, then the average is T(n)/n < 2n/n = 2 = \Theta (1). In this case we say that a single increment operation takes \Theta (1) amortized time: each increment takes \Theta (1) “on average”, even though an individual increment operation could take longer.
So how can we actually prove this? There are (at least) three methods; we will cover two of them.