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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code