Skip to content
BytePatterns

Total Bit Differences Across Pairs

MediumBit Manipulation#bit-counting#per-bit-contribution~20m

Problem

A network team compares device fingerprints stored as non-negative integers below 2^30. The difference between two fingerprints is the number of bit positions where they differ. Given a list of fingerprints, return the sum of the differences over every unordered pair. The list has up to 10,000 values, so XOR-ing every pair is too slow.

Examples

Input:  nums = [4, 14, 2]
Output: 6
Why:    4 vs 14 differ in 2 bits, 4 vs 2 in 2, 14 vs 2 in 2
Input:  nums = [4, 14, 4]
Output: 4
Input:  nums = [7]
Output: 0
Why:    edge case, one value makes no pairs

Hints

0 / 3

Stuck on the idea rather than the code? Counting Set Bits covers it.