Engineering platform~20 min2s · 256 MBtarget O(32 n) time, O(n) spacebit-manipulation · hashing
The platform team of an app stores each user's 32 feature flags in one whole number. Each flag is one bit, and the top bit is the sign bit. A rollout dashboard wants to see how similar users are.
Two users are one flag apart when their numbers differ in exactly one bit. Your team lead asks: "How many pairs of users are one flag apart?" There can be 100,000 users.
Write count_one_flag_apart(flags).
flags[i] is the flag word of user i, a 32-bit whole number. It may be negative, and the sign bit is one of the 32 flags.i < j whose words differ in exactly one of the 32 bits.Input: flags = [5, 7, 3, 6]
Output: 3Look at the bits that differ between each pair. In 3 bits, 5 is 101, 7 is 111, 3 is 011 and 6 is 110.
| Pair | Words | XOR of the words | Bits that differ | One flag apart? |
|---|---|---|---|---|
| 5 and 7 | 101, 111 |
010 |
1 | yes |
| 5 and 3 | 101, 011 |
110 |
2 | no |
| 5 and 6 | 101, 110 |
011 |
2 | no |
| 7 and 3 | 111, 011 |
100 |
1 | yes |
| 7 and 6 | 111, 110 |
001 |
1 | yes |
| 3 and 6 | 011, 110 |
101 |
2 | no |
Three pairs are one flag apart.
Input: flags = [0, -2147483648]
Output: 1-2147483648 has only bit 31, the sign bit, set. It differs from 0 in exactly that one bit.
Input: flags = [4, 4, 4]
Output: 0Equal words differ in no flag, so none of the 3 pairs counts.
1 ≤ len(flags) ≤ 100,000-2,147,483,648 ≤ flags[i] ≤ 2,147,483,647Looking at every pair means about 5 billion pairs for 100,000 users, which is too slow. The number of pairs itself can be as large as 2.5 billion, which does not fit in a 32-bit int, so the answer is a 64-bit number. And each word has only 32 possible partners one flag apart, so you can look up those 32 words instead of comparing with every other user.