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 INPUT nums = [4, 14, 2] 4 14 2 Binary Representation: 4 = 0100 14 = 1110 2 = 0010 Bit positions: 3 2 1 0 0 1 0 0 = 4 1 1 1 0 = 14 0 0 1 0 = 2 ALGORITHM STEPS 1 Count bits per position For each bit, count 1s and 0s 2 Bit 3: ones=1, zeros=2 Contribution: 1 * 2 = 2 3 Bit 2: ones=2, zeros=1 Contribution: 2 * 1 = 2 4 Bit 1: ones=2, zeros=1 Contribution: 2 * 1 = 2 Calculation Summary Bit 3: 1 x 2 = 2 Bit 2: 2 x 1 = 2 Bit 1: 2 x 1 = 2 Bit 0: 0 x 3 = 0 Total = 2+2+2+0 = 6 FINAL RESULT Output: 6 Verification (Brute Force): Pair (4,14): 0100 XOR 1110 = 1010 --> 2 Pair (4,2): 0100 XOR 0010 = 0110 --> 2 Pair (14,2): 1110 XOR 0010 = 1100 --> 2 2 + 2 + 2 = 6 OK - Verified! Key Insight: Instead of comparing all pairs O(n^2), count bits at each position. For position i, if there are 'c' ones and 'n-c' zeros, contribution = c * (n-c). Different bits create Hamming distance. Time: O(32*n) = O(n) | Space: O(1) TutorialsPoint - Total Hamming Distance | Optimal Solution (Bit Counting)
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