Chat app~25 min2s · 256 MBtarget O(bits) time, O(1) spacecomplexity · bit-manipulation
A chat app numbers the messages of a shard with a counter stored in a fixed number of bits. Each new message adds 1 to the counter. The storage layer writes only the bits that change, and when the counter passes its largest value it wraps to 0 and rewrites every bit.
The team wants the total bit writes of a run of messages, to see how the storage wears. You will count the flips exactly.
Write total_flips(bits, start, increments).
bits bits and starts at the value start, with 0 ≤ start < 2^bits.2^bits - 1, it wraps to 0.increments increments.Input: bits = 3, start = 0, increments = 8
Output: 14A 3-bit counter from 0, incremented 8 times. The last increment wraps from 111 to 000 and flips all 3 bits.
| Increment | Before | After | Flips | Total |
|---|---|---|---|---|
| 1 | 000 | 001 | 1 | 1 |
| 2 | 001 | 010 | 2 | 3 |
| 3 | 010 | 011 | 1 | 4 |
| 4 | 011 | 100 | 3 | 7 |
| 5 | 100 | 101 | 1 | 8 |
| 6 | 101 | 110 | 2 | 10 |
| 7 | 110 | 111 | 1 | 11 |
| 8 | 111 | 000 | 3 | 14 |
The total is 14, which is 2^4 - 2.
Input: bits = 4, start = 13, increments = 5
Output: 10A 4-bit counter from 13 passes 15 and wraps.
| Increment | Before | After | Flips | Total |
|---|---|---|---|---|
| 1 | 1101 | 1110 | 2 | 2 |
| 2 | 1110 | 1111 | 1 | 3 |
| 3 | 1111 | 0000 | 4 | 7 |
| 4 | 0000 | 0001 | 1 | 8 |
| 5 | 0001 | 0010 | 2 | 10 |
Input: bits = 1, start = 0, increments = 0
Output: 0With no increments, no bit flips: 0.
1 ≤ bits ≤ 39 (bits in the counter)0 ≤ start < 2^bits (starting value)0 ≤ increments ≤ 1,000,000,000,000 (messages)Incrementing one at a time takes up to 10^12 steps. The flips are at most 2 for each increment on average, so the total is about 2 × 10^12, which needs 64-bit integers. Each bit flips on a fixed rhythm, so a formula over the bits is enough.