The Hamming distance between two whole numbers is how many bit positions they differ in when written in binary.
You are given an array nums. Add up the Hamming distance of every pair of numbers in it (each unordered pair once) and return the sum.
Example 1
Input: nums = [6, 9, 3] Output: 8 Why: the pairs differ in 4, 2 and 2 bits
2 more examples and the constraints
Example 2
Input: nums = [7, 7] Output: 0 Why: equal numbers differ nowhere
Example 3
Input: nums = [1, 2, 4, 8] Output: 12 Why: each of the 6 pairs differs in 2 bits
Constraints
- 1 ≤ length of nums ≤ 10,000
- 0 ≤ nums[i] ≤ 1,000,000,000
- The answer fits in a 32-bit signed integer
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Every pairO(n²)
- Count each bit columnO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 numbers | Verdict |
|---|---|---|---|
| Every pair | O(n²) | Too slow at the limit | |
| Count each bit column | O(30 · n) | Best; one count per bit |
n = length of nums; 30 = bits needed for values up to 10⁹.
Edge cases to test
- One number. There are no pairs, so the answer is 0.
- All numbers equal. Every column is all 0s or all 1s, so k · (n − k) is 0 everywhere.
- Zeros. 0 has no set bits; it still counts as a 0 in every column.
- Large values. 1,000,000,000 uses bit 29, so the loop must go up to bit 29, not stop at 16.
Common mistakes
- Looping over bits only up to 16 or 20, missing the high bits of large values.
- Counting ordered pairs and getting twice the answer.
- Computing ones × ones or n × ones instead of ones × (n − ones).
How to talk through it
- 1Clarify. Are the numbers non-negative? Is each unordered pair counted once?
- 2Give the brute force. XOR every pair and count the 1s; O(n²), about 50 million pairs at the limit.
- 3Switch what you loop over. Bits are independent, so count per position instead of per pair.
- 4State the formula. k ones and n − k zeros in a column give k · (n − k) differing pairs.
- 5Test out loud. Run [6, 9, 3] column by column, then a single number and all-equal numbers.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?