885809. Total Hamming Distance

Medium

Total Hamming Distance

Summary

The Total Hamming Distance problem involves calculating the total Hamming distance between all pairs of binary strings in an array. The Hamming distance is defined as the number of positions at which two strings differ. This problem requires an understanding of bitwise operations and array manipulation.

Detailed Explanation

To solve this problem, we will use a combination of bitwise operations and array manipulation. We can calculate the total Hamming distance by iterating over all pairs of binary strings in the array and calculating their Hamming distances. We then sum up these Hamming distances to get the total Hamming distance.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable total_distance to 0, which will store the total Hamming distance.
  2. Iterate over all pairs of binary strings in the array using two nested loops.
  3. For each pair of strings, calculate their Hamming distance by iterating over the bits and counting the number of positions at which they differ.
  4. Add the Hamming distance to total_distance.
  5. Return total_distance as the total Hamming distance.

Here's a diagram illustrating the steps:

    +---------------+
    |  Iterate over  |
    |  all pairs of   |
    |  binary strings |
    +---------------+
           |
           v
    +---------------+
    |  Calculate     |
    |  Hamming       |
    |  distance for  |
    |  each pair     |
    +---------------+
           |
           v
    +---------------+
    |  Add Hamming   |
    |  distance to    |
    |  total_distance|
    +---------------+

Time complexity: O(n^2), where n is the number of binary strings in the array. Space complexity: O(1), as we only use a constant amount of space.

Optimized Solutions

Java

View on GeeksforGeeks
public int totalHammingDistance(int[] nums) {
    int total_distance = 0;
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            int hamming_distance = 0;
            for (int k = 0; k < 32; k++) {
                int bit_i = ((nums[i] >> k) & 1);
                int bit_j = ((nums[j] >> k) & 1);
                if (bit_i != bit_j) hamming_distance++;
            }
            total_distance += hamming_distance;
        }
    }
    return total_distance;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.