Part A: count the flips one bit position at a time
Bit 0 flips on every increment, bit 1 on every second, and bit every . From 0 to the
total is . For
(binary 1111101000, six 1s) that is . The average is under 2 per increment.
Part B: the boundary between two powers of two
Increment and every bit flips; decrement again and every bit flips back. Start at
32,767 (fifteen 1s) and alternate I and D: each operation flips all 16 bits, so 100 operations
flip 1,600 bits. The amortized argument for increments charged each carry to the increments
that built up the 1s, and a decrement throws that credit away.
Part C: signed digits, and a potential that pays for the cascades
Allow digits . To increment, clear the run of 1s at the bottom and add 1 to the next
digit. To decrement, clear the run of s and subtract 1. Now crossing a power of two and coming
back costs one write each way: after , the decrement turns the last
digit into , giving , and the next increment turns it back into 0.
Take as potential the number of nonzero digits. An increment that clears ones writes
cells and lowers by , then raises it by at most 1. Its amortized cost is at most
, and decrements are symmetric. Starting from , any operations
write at most cells. On the grader's sequences that came to between 1.3 and 2 writes per
operation, while plain binary needed 5.6 on the climb-and-alternate sequence.
Outside this problem's single row of cells there is a simpler trick: two plain counters, one for
arrivals and one for departures, with the count their difference. Each only ever increments, so
each costs at most 2 writes per operation amortized. Part C asks for one row of digits, which is
what forces the signed digits.
Going further
- Worst case, not just amortized. Redundant number systems with digits in and a
regularity invariant (between any two 2s there is a 0) support increments with writes
every time. The same idea gives worst-case bounds for heaps and lists built like numbers.
Okasaki's book develops these "numerical representations".
- The potential method is the tool behind
Union-Find and Splay Trees: pick a potential
that drops exactly when the expensive work happens.
References
- R. E. Tarjan. Amortized computational complexity. SIAM Journal on Algebraic and Discrete
Methods 6(2), 1985.
- C. Okasaki. Purely Functional Data Structures, chapter 9 (numerical representations).
Cambridge University Press, 1998.