Saturday, October 5, 2019

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.

class Solution {
public:
// Method to count 1s in a num
    int count_ones(int num) {
        int count = 0;
        for (int i = 0; i < 32; i++) {
            if (num & (1 << i)) {
                count++;
            }
        }
        return count;
    }

// Method to count 1s in a num.
    int count_ones_2(int num) {
        int count = 0;
        while (num != 0) {
            count++;
            num = (num & (num - 1));
        }
        return count;
    }

// Count the difference in bits in two numbers.
    int hamm_dist(int num1, int num2) {
        int count = 0;
        int helper;
        int pos = max((int)log2(num1), (int)log2(num2));
        for (int i = 0; i <= pos; i++) {
            helper = 1 << i;
            count += count_ones_2((num1 & helper) ^ (num2 & helper));
           
        }
        return count;
    }
   
// Brute force.
    int totalHammingDistance_normal_approach(vector<int>& nums) {
        int ans = 0;
        int size = nums.size();
        for (int i = 0; i < size; i++) {
            for (int j = i + 1; j < nums.size(); j++) {
                ans += hamm_dist(nums[i], nums[j]);
            }
        }
        return ans;
    }
   

// ============= Efficient one =============
    int totalHammingDistance(vector<int>& nums) {
        int total = nums.size();
        vector<int> tmp(32, 0);
        for (int i = 0; i < total; i++) {
            int num = nums[i];
            int iter = 0;         
            while (num != 0) {
                if (num & 1) {
                    tmp[iter]++;
                }
                num >>= 1;
                iter++;
            }
        }

        int ans = 0;
        for (int i = 0; i < tmp.size(); i++) {
            ans += tmp[i]*(total - tmp[i]);
        }
        return ans;
    }
};

No comments:

Post a Comment