codejump
MediumPythonJavaScriptTypeScript

Bits — Total Hamming Distance

AlgorithmsBit ManipulationMath

The Hamming distance of two integers is the number of bit positions where they differ.
solve(nums) — nums holds non-negative integers < 2^31. Return the **sum of the Hamming
distances over all pairs** (i, j) with i < j.

Comparing every pair is O(n²). Count per bit instead: if ones of the n numbers
have a given bit set, then ones × (n - ones) pairs differ on that bit. Sum that over
the 31 bit positions for an O(31 · n) solution.

Examples

solve([4,14,2])   → 6
solve([4,14,4])   → 4
solve([1,2,3])    → 4

Sample tests

Test #1Classic example
Input: [[4,14,2]]
Output: 6
Test #2Repeated value
Input: [[4,14,4]]
Output: 4
Test #3Three small values
Input: [[1,2,3]]
Output: 4