#477
Total Hamming Distance
MediumArrayMathBit ManipulationBit ManipulationArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of calculating the Hamming distance for every pair, we can count how many numbers have a bit set at each position. This allows us to compute the contribution of each bit position to the total Hamming distance more efficiently.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a variable to store the total Hamming distance.
- 2Step 2: Iterate through each bit position from 0 to 31 (since nums[i] <= 10^9 fits in 32 bits).
- 3Step 3: For each bit position, count how many numbers have that bit set (1) and how many do not (0).
- 4Step 4: The contribution to the total Hamming distance from this bit position is the product of the count of 1s and 0s.
- 5Step 5: Add this contribution to the total.
solution.py13 lines
1# Full working Python code
2
3def totalHammingDistance(nums):
4 total = 0
5 n = len(nums)
6 for i in range(32):
7 count_one = sum((num >> i) & 1 for num in nums)
8 count_zero = n - count_one
9 total += count_one * count_zero
10 return total
11
12# Example usage
13print(totalHammingDistance([4, 14, 2])) # Output: 6ℹ
Complexity note: The time complexity is O(n) because we iterate through the array a constant number of times (32 for each bit position). The space complexity is O(1) since we only use a fixed amount of extra space.
- 1The Hamming distance is fundamentally about comparing bits, so understanding bit manipulation is crucial.
- 2Counting contributions from each bit position is more efficient than brute-force pairwise comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.