Total Hamming Distance - Problem
Total Hamming Distance
The Hamming distance between two integers is the number of bit positions where the corresponding bits differ. For example, the Hamming distance between
Given an integer array
Goal: Return the total sum of Hamming distances for all possible pairs
Example: For
• Hamming distance between 4 and 14:
• Hamming distance between 4 and 2:
• Hamming distance between 14 and 2:
• Total:
The Hamming distance between two integers is the number of bit positions where the corresponding bits differ. For example, the Hamming distance between
4 (binary: 100) and 14 (binary: 1110) is 2 because they differ at the 2nd and 3rd bit positions.Given an integer array
nums, your task is to calculate the sum of Hamming distances between all pairs of integers in the array.Goal: Return the total sum of Hamming distances for all possible pairs
(i, j) where i < j.Example: For
[4, 14, 2], we calculate:• Hamming distance between 4 and 14:
2• Hamming distance between 4 and 2:
2• Hamming distance between 14 and 2:
2• Total:
2 + 2 + 2 = 6 Input & Output
example_1.py — Basic case
$
Input:
[4, 14, 2]
›
Output:
6
💡 Note:
Hamming distances: hamming(4,14) + hamming(4,2) + hamming(14,2) = 2 + 2 + 2 = 6. Breaking it down: 4(100₂) vs 14(1110₂) differs in 2 positions, 4(100₂) vs 2(010₂) differs in 2 positions, 14(1110₂) vs 2(010₂) differs in 2 positions.
example_2.py — Single element
$
Input:
[1]
›
Output:
0
💡 Note:
Only one number in array, so no pairs exist. Total Hamming distance is 0.
example_3.py — Identical numbers
$
Input:
[5, 5, 5]
›
Output:
0
💡 Note:
All numbers are identical (101₂), so Hamming distance between any pair is 0. Total: 0 + 0 + 0 = 0.
Constraints
- 1 ≤ nums.length ≤ 3 × 104
- 0 ≤ nums[i] ≤ 109
- Time limit: The solution must handle the maximum input size efficiently
Visualization
Tap to expand
Understanding the Visualization
1
Setup Checkpoints
Examine each of the 32 bit positions as security checkpoints
2
Count Access Patterns
For each checkpoint, count how many fingerprints show '1' (access granted) vs '0' (access denied)
3
Calculate Mismatches
At each checkpoint, mismatches occur between '1' and '0' groups. Total mismatches = count_1s × count_0s
4
Sum All Checkpoints
Add up mismatches from all 32 checkpoints to get total Hamming distance
Key Takeaway
🎯 Key Insight: By analyzing bit positions independently rather than comparing pairs, we transform an O(n²) problem into an O(n) solution using the mathematical relationship: total_distance = Σ(count_1s × count_0s) across all bit positions.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code