VOOZH about

URL: https://www.geeksforgeeks.org/dsa/total-hamming-distance/

⇱ Total Hamming Distance - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Total Hamming Distance

Last Updated : 1 Apr, 2026

Given an integer array arr[], return the sum of Hamming distances between all the pairs of the integers in arr.

The Hamming distance between two integers is the number of bit positions at which the corresponding bits are different.

Note: The answer is guaranteed to fit within a 32-bit integer.

Examples:

Input: arr[] = [1, 14]
Output: 4
Explanation: Binary representations of 1 is 0001, 14 is 1110. The answer will be:
hammingDist(1, 14) = 4.

Input: arr[] = [4, 14, 4, 14]
Output: 8
Explanation: Binary representations of 4 is 0100, 14 is 1110. The answer will be:
hammingDist(4, 14) + hammingDist(4, 4) + hammingDist(4, 14) + hammingDist(14, 4) + hammingDist(14, 14) + hammingDist(4, 14) = 2 + 0 + 2 + 2 + 0 + 2 = 8.

[Naive Approach] - Checking Each Pair - O(n^2) Time and O(1) Space

Iterate over all pairs using nested loops and compute the Hamming distance by comparing their bits. For each bit position, increment the count if the bits differ. Sum all such counts to obtain the total Hamming distance across all pairs.

  • Initialize a variable count to store the total Hamming distance.
  • Use two loops to iterate over all unique pairs (i, j) such that j > i.
  • For each pair, loop through all bit positions from 0 to 30.
  • Check if the k-th bit of both numbers is different. If yes, then increment count.
  • Return count

Output
8

[Expected Approach] - Bitwise Frequency Counting Using Array - O(n) Time and O(1) Space

Count the number of 1s at each bit position (0 to 31) across all numbers. For each bit, multiply the number of 1s with the number of 0s to get its contribution to the total Hamming distance.

  • Initialize count as 0.
  • Create a countone array of size 32 initialized to 0.
  • Traverse each element of the array.
  • For every number, iterate through bit positions 0 to 31.
  • Check if the j-th bit is set. If set, increment countone[j].
  • For each bit, compute contribution as countone[j] * (n - countone[j]) and add to count.
  • Return count

Output
8
Comment
Article Tags:
Article Tags: