Total Hamming Distance
Total Hamming Distance is LeetCode 477 (Medium). The Hamming distance between two integers is the number of bit positions where their bits differ. Given an integer array nums, return the sum of Hamming distances of all pairs of numbers.
- Each pair is counted once.
- The answer fits in a 32-bit integer.
With up to 10⁴ numbers there are about 5 × 10⁷ pairs, so comparing pairs one by one is too slow. Every number is at most 10⁹, which is below 2³⁰, so only bits 0 to 29 can ever be set.
- 1 <= nums.length <= 10⁴
- 0 <= nums[i] <= 10⁹
- The answer for the given input will fit in a 32-bit integer.
Intuition
Turn the sum around. Instead of asking how many bits each pair differs in, ask how many pairs differ at each bit. The total is the same, because every differing bit of every pair is counted exactly once either way.
At one bit position, a pair differs only when one number has a 1 there and the other has a 0. If ones numbers have a 1, the other n − ones have a 0, and every 1 can be matched with every 0. So that bit adds ones × (n − ones) to the answer, with no pair ever looked at directly.
"Sum something over all pairs" where the something splits into independent parts (here, bits) is a counting problem in disguise. Count how many items fall on each side of each part and multiply, instead of looping over pairs.
Approach
Before reading on, pick one bit position and think about which pairs differ there. If you knew only how many numbers have a 1 at that bit, could you say how many pairs differ at it? Aim for O(n) for 30 bits.
Go through bit positions 0 to 29
Every number is at most 10⁹ and 2³⁰ is 1,073,741,824, so bit 30 and above are 0 in every number. A bit that is 0 everywhere adds nothing, so 30 positions are enough.
Count the ones at this bit
For each number, add (num >> b) & 1 to ones. Shifting moves bit b to the last place and & 1 keeps only that bit, so it adds 1 exactly when the bit is set.
Add ones × zeros
After the whole array is counted, add ones * (n - ones) to the total. Each number with a 1 differs from each number with a 0 at this bit, and each such pair is counted once.
Return the total
Summed over all 30 bits, the total counts every differing bit of every pair exactly once, which is exactly the sum of all the Hamming distances, so return it.
Code in Python, C++ and Java
Common pitfalls
Counting every pair twice
total += 2 * ones * (n - ones)
total += ones * (n - ones)
ones × (n − ones) already matches each 1 with each 0 once. Doubling it (or summing over both orders i, j and j, i in a pair loop) counts every pair twice: [4, 14, 2] gives 12 instead of 6.
Checking too few bits
for b in range(16):
for b in range(30):
Values go up to 10⁹, which needs 30 bits. With 16 bits, [0, 65536] returns 0, because 65536 = 2¹⁶ has its only 1 at bit 16, and the right answer is 1.
Edge cases
[5, 5] or [7]At every bit either all numbers have a 1 or none do, so ones × (n − ones) is 0 each time and the total is 0.
Complexity
ones and total are stored.Total Hamming Distance FAQ
Can the total overflow a 32-bit int?
Not within these limits. At one bit, ones × (n − ones) is largest when the numbers split evenly: 5,000 × 5,000 = 2.5 × 10⁷ for n = 10⁴. Even if all 30 bits hit that, the total is 7.5 × 10⁸, below the int limit of about 2.1 × 10⁹.
Why not XOR each pair and count its bits?
It is correct, since a ^ b has a 1 exactly where a and b differ, but it costs O(n²). For 10⁴ numbers that is about 5 × 10⁷ pairs, which is too slow in Python and wasteful anywhere. The per-bit count does the same job in about 3 × 10⁵ steps.
Is this the same as the sum of bit differences among all pairs?
Almost. That version counts ordered pairs, so (a, b) and (b, a) are both included and its answer is exactly twice this one: 2 × ones × (n − ones) per bit. For [1, 3, 5] it gives 8, while the total Hamming distance is 4.
How is this different from Hamming Distance (LeetCode 461)?
LeetCode 461 asks for the distance between just two numbers, which is the count of ones in x ^ y. Here the question is the sum over every pair in an array, so XOR per pair would be quadratic and the per-bit count is what makes it linear.