Given an integer array nums
, return the sum of Hamming distances between all the pairs of the integers in the array.
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Example 1:
Input: nums = [4, 14, 2]
Output: 6
Explanation: There are 3 pairs:
(4, 14) with Hamming distance 2,
(4, 2) with Hamming distance 2,
(14, 2) with Hamming distance 2.
So the total Hamming distance is 2 + 2 + 2 = 6.
Example 2:
Input: nums = [4,14,4]
Output: 4
Constraints:
1 <= nums.length <= 10^4
0 <= nums[i] <= 10^9
To solve this problem efficiently, calculating the Hamming distance for each pair of numbers traditionally would be computationally expensive ((O(n^2 \cdot 32))). Instead, we can use the following optimized approach:
k
numbers have the bit set, and n
is the total number of numbers, then (n - k)
numbers have the bit unset.k * (n - k)
.This approach has a time complexity of (O(n \cdot 32)) which is linear in terms of the number of elements, and hence, should be efficient given the constraints.
def totalHammingDistance(nums):
total = 0
n = len(nums)
for i in range(32):
bit_count = 0
for num in nums:
bit_count += (num >> i) & 1
total += bit_count * (n - bit_count)
return total
# Example usage:
nums = [4, 14, 2]
print(totalHammingDistance(nums)) # Output: 6
This solution ensures that we efficiently compute the total Hamming distance across all pairs in the given integer array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?