Total Hamming Distance
Master this topic with zero to advance depth.
Total Hamming Distance
The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Return the sum of Hamming distances between all pairs of integers in nums.
Examples
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
Level I: Brute Force (Check All Pairs)
Intuition
The most direct way is to iterate through every pair in the array, calculate their Hamming distance, and sum them up.
Thought Process
- Initialize
totalDist = 0. - For each pair where :
- Calculate Hamming distance:
Integer.bitCount(nums[i] ^ nums[j]). - Add to
totalDist.
- Calculate Hamming distance:
- Return
totalDist.
Pattern: Nested Iteration
Level II: Iterative Bit Verification
Intuition
We can calculate the Hamming distance for each pair by iterating through the numbers and checking each bit. This is similar to the brute force but slightly more structured.
Level III: Optimal (Bit Counting per Position)
Intuition
Instead of checking pairs, we can check bit positions. For any bit position , if numbers have the -th bit set to 1, and numbers have it set to 0, then there are pairs that differ at this position.
Thought Process
- Initialize
total = 0. - For each bit position to :
- Count numbers with -th bit set.
total += k * (n - k).
- Return
total.
Pattern: Positional Counting
Detailed Dry Run
nums: [4, 14, 2], n=3 Bit Pos 1: Bits are {0, 1, 0}. k=1, n-k=2. Pairs = 12 = 2. Bit Pos 2: Bits are {1, 1, 0}. k=2, n-k=1. Pairs = 21 = 2. Bit Pos 3: Bits are {0, 1, 0}. k=1, n-k=2. Pairs = 1*2 = 2. Total: 2+2+2 = 6.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.