← All problemsFree · Python · 45 min

Algorithm design / guarantees under an adversary

The Turnstile Counter

A binary counter costs 2 bit flips per increment on average, until it also has to count down. Find the sequence that makes it expensive, then design a counter whose increments and decrements both cost O(1) amortized writes.

0 / 3 graded parts passSaved in this browser · loading saved work…
Jump to your work ↓

A stadium turnstile keeps a running count of the people inside, as a binary number in a row of switches. Each switch costs a little wear every time it flips, so the cost of an operation is the number of switches it flips. People come in (increment) and go out (decrement).

4 switches counting up from 0: an increment costs the switches it flips00000100011 flip200102 flips300111 flip401003 flips501011 flip601102 flips701111 flip810004 flips8 increments, 15 flips in all
Counting up from 0 to 8: the switches each increment flips are shaded.

Counting up only, the classic amortized analysis says each increment flips about 2 switches on average. Does that survive people leaving? And if not, can a different way of storing the count make both directions cheap?

The counter in part C

The count is kept in 64 cells d[0] to d[63], and its value is ∑idi2i, so plain binary is the case where every cell holds 0 or 1. Your counter may also use the digits −1 and 2. The cost is the number of writes: every assignment d[i] = ... counts, even one that writes the value already there. The grader reads the value from the cells after every operation.

Background: Amortized Analysis.

easy · Part A

Counting up is cheap

A plain binary counter starts at 0 and is incremented 1,000 times. How many bit flips is that in total?

Explore in the sandbox

Experiment here, then copy a rule into the editor and test its guarantees.