LeetCode #477 Medium

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.

Constraints
  • 1 <= nums.length <= 10⁴
  • 0 <= nums[i] <= 10⁹
  • The answer for the given input will fit in a 32-bit integer.
bit-manipulationmath
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def totalHammingDistance(self, nums):
▶3 n = len(nums)
▶4 total = 0
▶5 for b in range(30):
▶6 ones = 0
▶7 for num in nums:
▶8 ones += (num >> b) & 1
▶9 total += ones * (n - ones)
▶10 return total
bit01234001014011120100onespairs0addstotal04 has a 0 at bit 0 → ones stays 0
b0
num4
ones0
Shift 4 right by 0 and keep the last bit: it is 0. Only this bit matters right now, so the other columns are greyed out.
bit01234001014011120100onespairs0addstotal014 has a 0 at bit 0 → ones stays 0
b0
num14
ones0
Shift 14 right by 0 and keep the last bit: it is 0. Numbers with a 0 here are counted later as n − ones.
bit01234001014011120100onespairs0addstotal02 has a 0 at bit 0 → ones stays 0
b0
num2
ones0
Shift 2 right by 0 and keep the last bit: it is 0. Numbers with a 0 here are counted later as n − ones.
bit01234001014011120100onespairs00adds0×3=0oneszerostotal0bit 0: 0 ones × 3 zeros → adds 0
ones0
zeros3
total0
All 3 numbers agree at this bit (all 0s), so no pair differs here and the total does not change.
bit01234001014011120100onespairs000addstotal04 has a 0 at bit 1 → ones stays 0
b1
num4
ones0
Shift 4 right by 1 and keep the last bit: it is 0. Numbers with a 0 here are counted later as n − ones.
bit01234001014011120100onespairs001addstotal014 has a 1 at bit 1 → ones is 1
b1
num14
ones1
Shift 14 right by 1 and keep the last bit: it is 1. One more number has a 1 at bit 1.
bit01234001014011120100onespairs002addstotal02 has a 1 at bit 1 → ones is 2
b1
num2
ones2
Shift 2 right by 1 and keep the last bit: it is 1. One more number has a 1 at bit 1.
bit01234001014011120100onespairs0022adds2×1=2oneszerostotal2bit 1: 2 ones × 1 zero → adds 2
ones2
zeros1
total2
Each of the 2 numbers with a 1 differs from the 1 number with a 0 at this bit, so 2 pairs differ here. Each pair is counted once, from the 1 side.
bit01234001014011120100onespairs00221addstotal24 has a 1 at bit 2 → ones is 1
b2
num4
ones1
Shift 4 right by 2 and keep the last bit: it is 1. One more number has a 1 at bit 2.
bit01234001014011120100onespairs00222addstotal214 has a 1 at bit 2 → ones is 2
b2
num14
ones2
Shift 14 right by 2 and keep the last bit: it is 1. One more number has a 1 at bit 2.
bit01234001014011120100onespairs00222addstotal22 has a 0 at bit 2 → ones stays 2
b2
num2
ones2
Shift 2 right by 2 and keep the last bit: it is 0. Numbers with a 0 here are counted later as n − ones.
bit01234001014011120100onespairs002222adds2×1=2oneszerostotal4bit 2: 2 ones × 1 zero → adds 2
ones2
zeros1
total4
Each of the 2 numbers with a 1 differs from the 1 number with a 0 at this bit, so 2 pairs differ here. Each pair is counted once, from the 1 side.
bit01234001014011120100onespairs0022220addstotal44 has a 0 at bit 3 → ones stays 0
b3
num4
ones0
Shift 4 right by 3 and keep the last bit: it is 0. Numbers with a 0 here are counted later as n − ones.
bit01234001014011120100onespairs0022221addstotal414 has a 1 at bit 3 → ones is 1
b3
num14
ones1
Shift 14 right by 3 and keep the last bit: it is 1. One more number has a 1 at bit 3.
bit01234001014011120100onespairs0022221addstotal42 has a 0 at bit 3 → ones stays 1
b3
num2
ones1
Shift 2 right by 3 and keep the last bit: it is 0. Numbers with a 0 here are counted later as n − ones.
bit01234001014011120100onespairs00222212adds1×2=2oneszerostotal6bit 3: 1 one × 2 zeros → adds 2
ones1
zeros2
total6
The 1 number with a 1 differs from each of the 2 numbers with a 0 at this bit, so 2 pairs differ here. Each pair is counted once, from the 1 side.
bit01234001014011120100onespairs00222212adds0 in every numbertotal6bits 4 to 29: every number has 0 → adds 0
b4 … 29
total6
The loop still visits bits 4 to 29, but every number here is below 24, so each of those bits has 0 ones and adds 0 × 3 = 0. Bits are only drawn while some number has a 1.
bit01234001014011120100onespairs00222212addsevery bit countedtotal6answer: 6
return6
Adding the pairs row gives 0 + 2 + 2 + 2 = 6. Every differing bit of every pair was counted exactly once, and no pair was ever compared directly.
05

Common pitfalls

Counting every pair twice

✗ Wrong
total += 2 * ones * (n - ones)
✓ Right
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

✗ Wrong
for b in range(16):
✓ Right
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.

06

Edge cases

All numbers equal, including a single number, e.g. [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.

07

Complexity

Time
O(n)
Space
O(1)
30 passes over the n numbers, so about 30n steps, which is linear because 30 is fixed by the value range. Only ones and total are stored.
08

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.