[LeetCode] 477. Total Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the given numbers.
Example:
Input: 4, 14, 2

Output: 6

Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case). So the answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
Note:
  1. Elements of the given array are in the range of to 10^9
  2. Length of the array will not exceed 10^4.

Thought process:
A naive solution is to wrap a nested loop around the solution of "461. Hamming Distance". This results in quadratic time complexity, which exceeds the time limit.
A more efficient way to solve this is to iterate through the bits. Since max(nums) < 10^9, I know that the numbers won't take more than 32 bits. Say for one of these bits, there are k numbers with that bit on, so there are n - k numbers with that bit off. Then that particular bit will add k(n - k) to the total hamming distance.

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    public int totalHammingDistance(int[] nums) {
        int[] bitCounts = new int[32];
        for (int num : nums) {
            int i = 0;
            while (num > 0) {
                bitCounts[i] += num & 1;
                num >>= 1;
                i++;
            }
        }
        
        int length = nums.length;
        int total = 0;
        for (int count : bitCounts) {
            total += count * (length - count);
        }
        return total;
    }
}

Time complexity:
Say there are n numbers. The first for loop takes O(n log(max(nums))). Since max(nums) < 10^9, log(max(nums)) is constant. So the first for loop takes O(n). The second for loop takes O(1). So the overall time complexity is O(n).

Comments

Popular posts from this blog

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee