Total Hamming Distance - Problem

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.

Example: For array [4, 14, 2], we need to find Hamming distances between all pairs: (4,14), (4,2), and (14,2), then sum them up.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4, 14, 2]
Output: 6
💡 Note: Hamming distances: H(4,14)=2 (100⊕1110=1010), H(4,2)=2 (100⊕010=110), H(14,2)=2 (1110⊕010=1100). Total = 2+2+2 = 6
Example 2 — Minimum Size
$ Input: nums = [4, 14]
Output: 2
💡 Note: Only one pair: H(4,14) = 2 (binary 100 vs 1110 differ in 2 positions)
Example 3 — Same Numbers
$ Input: nums = [1, 1, 1]
Output: 0
💡 Note: All numbers are identical, so Hamming distance between any pair is 0

Constraints

  • 1 ≤ nums.length ≤ 104
  • 0 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Total Hamming Distance Problem4142100₂1110₂010₂Input: [4, 14, 2]H(4,14)H(4,2)H(14,2)222100⊕1110100⊕0101110⊕010Total = 6Sum of all pairwise Hamming distances
Understanding the Visualization
1
Input
Array of integers to compare
2
Process
Calculate Hamming distance between all pairs
3
Output
Sum of all pairwise distances
Key Takeaway
🎯 Key Insight: Instead of comparing n² pairs, analyze each bit position once to count differing pairs mathematically
Asked in
Facebook 25 Google 20 Microsoft 15
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen