Three medium problems where every bit position is its own small problem. The move: keep a tiny state per bit inside one integer, and update all positions with a few bit operations.
You work on a monitoring service, a social feed and a ride-hailing app. The three problems on this street come from them. Each one has numbers where a bit trick can replace a map of counts, and each one asks for a lone value or a shared one.
The operations xor, and, or treat each position of a number independently of its neighbours. So you can think of a 30-bit number as 30 tiny problems that run side by side.
| Problem | What each bit position tracks | The tool |
|---|---|---|
| The alert only one monitor raised | how many ones it has seen, modulo 3 | two integers, ones and twos |
| The two posts only one data centre logged | whether it has seen an odd number of ones | xor, then a bit where the two differ |
| Shared flags of a block of vehicle ids | whether it stays the same across the block | the common prefix of the two ends |
A feed of 300,001 alerts would need a map of 100,001 counts if we used the usual tool. The bit tricks use two integers.
Here is the first problem on a small feed. The alert ids are 2, 2, 3 and 2, so the lone id appears once and the others three times. Watch how the two integers change.
Exercise · Predict the output: Two integers that count modulo 3. Here ones holds the bits seen once more than a multiple of three times, and twos holds the bits seen twice more. The feed is 2, 2, 3 and 2. What does the code print?
ones = 0
twos = 0
for x in [2, 2, 3, 2]:
ones = (ones ^ x) & ~twos
twos = (twos ^ x) & ~ones
print(ones, twos)The move has two parts.
First, ask what one bit position needs to remember. For "appears twice" it needs one bit, the parity of the ones seen, and xor keeps it. For "appears three times" it needs a count from 0 to 2, which is two bits. For a range it needs one flag: has this position ever changed?
Second, write the update for one position, then apply it to all positions at once. Bit operations work on every position of an integer together, so one line updates 30 positions.
Give every bit position its own small state, and store the states of all positions in a few integers. A line of bit operations then advances all positions together.
For a count modulo 3, the two integers together hold a count from 0 to 2 for each position. A position that has seen three ones returns to 0, so the ids that appear three times leave nothing behind.
The cost is the length of the feed times a few operations, and the memory is two integers. There is no map and no sort.
Two integers count each bit modulo 3. On the feed 2, 2, 3, 2 the lone id 3 is left in ones.
The update order matters, because twos reads the new value of ones.
Exercise · Find the bug: The prefix that lost its place. This returns the and of every number from lo to hi. It shifts both ends right until they are equal. It returns a wrong answer. Which line is wrong?
def shared_flags(lo, hi):
shift = 0
while lo != hi:
lo >>= 1
hi >>= 1
shift += 1
return loThe Academy lesson Bits and maths basics taught xor, shifts and masks, and Seen-set and complement used a map to find what is missing. This street changes three things.
The cancel becomes a count. Xor cancels a pair, so a number that appears twice vanishes. A number that appears three times does not vanish under xor, so we need a count modulo 3 for each bit. That is the pair of integers ones and twos.
A bit that differs splits the feed. When two lone numbers remain, the xor of everything is the xor of the two, and it is not zero because they differ. Its lowest set bit is a position where one lone number has 1 and the other has 0. Splitting the feed by that bit puts each lone number in its own group, and every pair stays together.
On the feed 1, 2, 1, 3, 2, 5 the xor is 6, the lowest set bit is 2, and the groups give 3 and 5.
The answer is a shared prefix. The and of a block of consecutive numbers keeps only the bits that never change. For lo = 5 and hi = 7 the answer is 4, not the and of the two ends, which is 5.
For lo = 1 and hi = 1,000,000,000, going through every number takes 1,000,000,000 steps. Shifting takes 30, and the answer is 0.
The and of 5 to 7 is 4. The ends give 5. Shift both ends until equal, then shift the prefix back.
Now put the two-lone-numbers solution in order.
Exercise · Put it in order: Split the feed by a bit. Arrange the lines into a function that returns the two lone ids, smaller first. Every other id appears twice.
def lone_posts(posts):
both = 0
one = 0
for x in posts:
both ^= x
low = both & -both
for x in posts:
if x & low:
one ^= x
return [min(one, both ^ one), max(one, both ^ one)]
low = both & (both - 1)A trick for one count does not carry over to another, as the next case shows.
Exercise · Break it: The xor that forgot the triples. In this feed every id appears three times except one lone id. This returns the lone id by xor of the whole feed, the trick that works when ids appear twice. Find an input where it is wrong.
def find_lone_alert(alerts):
lone = 0
for x in alerts:
lone ^= x
return loneSolve them in this order. The first needs a count modulo 3. The second reuses xor and adds a bit that splits the feed. The third keeps only the bits that never change.
Before you code each problem, write two lines: what one bit position must remember, and how many bits that takes. If the answer is one bit, xor may be enough. If it is two bits, you need two integers.
Give each problem about 20 minutes. Spend the first five on the two lines and on a trace of a feed of four numbers, written in binary.
Check these before you submit. Test a feed of one number. Test numbers whose high bits are all zero. Test negative numbers in languages where they matter, and use unsigned shifts if your language needs them.
Checkpoint · Bits and maths, in depth
Q1/5 In a feed where every id appears three times except one, what must each bit position remember?
Answer: B
A count from 0 to 2 needs two bits, and the integers ones and twos store them for all positions. Xor alone cancels only pairs.
Q2/5 Two lone ids remain after the xor of the whole feed, and the xor is 6. Why can you split the feed by the lowest set bit of 6?
Answer: C
A bit of the xor is 1 only where the two lone ids differ. The lowest set bit of 6 is 2, and the groups it makes put one lone id in each, with every pair together.
Q3/5 What is the and of every number from 5 to 7, and what do the ends alone give?
Answer: B
The numbers 5, 6 and 7 are 101, 110 and 111, and only the top bit is 1 in all three, which is 4. The ends alone are 101 and 111, and their and is 5.
Q4/5 The feed is 2, 2, 3, 2, where every id appears three times except one. What does the xor of the whole feed give?
Answer: B
Xor cancels only pairs. The three 2 values leave one 2 behind, and 2 xor 3 is 1. The count modulo 3 is the right tool.
Q5/5 What does it cost to find the and of every number from 1 to 1,000,000,000 by going through the numbers, and by shifting?
Answer: C
The two ends share no bits, so they become equal only after 30 shifts. The answer is 0, and the loop over the numbers is never needed.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.