Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Total Hamming Distance
Next article icon

Total Hamming Distance

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

We iterate through all pairs using nested loops and compute the Hamming distance for each pair by checking differing bits. For each bit position, if the two numbers have different values, we increment the total count. The final sum gives the total Hamming distance across all pairs.

C++
#include <bits/stdc++.h> using namespace std;  // Function to calculate the total Hamming distance between all pairs int totHammingDist(vector<int>& arr) {     int count = 0;     int n = arr.size();           // Loop through all unique pairs (i, j)     for (int i = 0; i < n; i++) {         for (int j = i + 1; j < n; j++) {              // For each bit position from 0 to 30             for (int k = 0; k < 31; k++) {                                   // If bit k is set in arr[i] and not in arr[j]                 if ((arr[i] & (1 << k)) && !(arr[j] & (1 << k))) {                     count++;                 }                  // If bit k is not set in arr[i] and is set in arr[j]                 else if (!(arr[i] & (1 << k)) && (arr[j] & (1 << k))) {                     count++;                 }             }         }     }      // Return the total count of differing bits (Hamming distance)     return count; }  int main() {     vector<int> arr = {4, 14, 4, 14};      int ans = totHammingDist(arr);     cout << ans << endl;      return 0; } 
Java
import java.util.*;  public class GfG {      // Function to calculate the total Hamming distance between all pairs     static int totHammingDist(int[] arr) {         int count = 0;         int n = arr.length;          // Iterate over all unique pairs (i, j)         for (int i = 0; i < n; i++) {             for (int j = i + 1; j < n; j++) {                  // For each bit position from 0 to 30                  for (int k = 0; k < 31; k++) {                      // Check if the k-th bit differs between                      // arr[i] and arr[j]                      // arr[i] has bit k set, arr[j] does not                     if (((arr[i] & (1 << k)) != 0) &&                                        ((arr[j] & (1 << k)) == 0)) {                         count++;                     }                      // arr[i] has bit k unset, arr[j] has it set                     if (((arr[i] & (1 << k)) == 0) &&                                       ((arr[j] & (1 << k)) != 0)) {                         count++;                     }                 }             }         }          // Return total Hamming distance         return count;     }      public static void main(String[] args) {                  int[] arr = {4, 14, 4, 14};         int ans = totHammingDist(arr);         System.out.println(ans);       } } 
Python
def totHammingDist(arr):     count = 0     n = len(arr)      # Loop through all unique pairs (i, j) in the array     for i in range(n):         for j in range(i + 1, n):              # For each bit position from 0 to 30              for k in range(31):                  # Check if the k-th bit is different between                 # arr[i] and arr[j]                  # k-th bit is set in arr[i] but not in arr[j]                 if (arr[i] & (1 << k)) and not (arr[j] & (1 << k)):                     count += 1                  # k-th bit is not set in arr[i]                  # but is set in arr[j]                 if not (arr[i] & (1 << k)) and (arr[j] & (1 << k)):                     count += 1      # Return total Hamming distance across all pairs     return count  # Driver code if __name__ == "__main__":     arr = [4, 14, 4, 14]     ans = totHammingDist(arr)     print(ans)   
C#
using System;  class GfG {          // Function to calculate total Hamming distance between     // all unique pairs in the array     static int totHammingDist(int[] arr) {         int count = 0;         int n = arr.Length;         // Loop through all unique pairs (i, j)         for (int i = 0; i < n; i++) {             for (int j = i + 1; j < n; j++) {                 // For each bit position from 0 to 30                  for (int k = 0; k < 31; k++) {                      // Check if the k-th bit is different between arr[i] and arr[j]                     // bit k is set in arr[i] but not in arr[j]                     if (((arr[i] & (1 << k)) != 0) &&                                    ((arr[j] & (1 << k)) == 0)) {                         count++;                     }                      // bit k is not set in arr[i] but is set in arr[j]                     if (((arr[i] & (1 << k)) == 0) &&                                          ((arr[j] & (1 << k)) != 0)) {                         count++;                     }                 }             }         }          // Return the total Hamming distance         return count;     }      // Main method to test the function     static void Main() {         int[] arr = { 4, 14, 4, 14 };         int ans = totHammingDist(arr);         Console.WriteLine(ans);       } } 
JavaScript
function totHammingDist(arr) {     let count = 0;     let n = arr.length;      // Loop through all unique pairs (i, j) in the array     for (let i = 0; i < n; i++) {         for (let j = i + 1; j < n; j++) {                          // For each bit position from 0 to 30              for (let k = 0; k < 31; k++) {                                  // Check if the k-th bit is different in arr[i] and arr[j]                 // k-th bit is set in arr[i] but not in arr[j]                 if ((arr[i] & (1 << k)) && !(arr[j] & (1 << k))) {                     count++;                 }                  // k-th bit is not set in arr[i] but is set in arr[j]                 if(!(arr[i] & (1 << k)) && (arr[j] & (1 << k))) {                      count++;                 }             }         }     }      // Return the total Hamming distance between all pairs     return count; }  // Driver code let arr = [4, 14, 4, 14]; let ans = totHammingDist(arr); console.log(ans);  

Output
8 

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

This approach counts the number of 1s at each bit position (0 to 31) across all numbers in the array. The total Hamming distance is calculated by multiplying the count of 1s with the count of 0s at each position, as every differing bit contributes to the total distance.

C++
#include <bits/stdc++.h> using namespace std;  // Function to calculate the total Hamming Distance  // among all pairs in the array int totHammingDist(vector<int> &arr){          int n = arr.size();              int count = 0;                   vector<int> countone(32, 0);          // Count how many numbers have the j-th bit set     for (int i = 0; i < n; i++){         for (int j = 0; j < 32; j++){                          // Check if j-th bit is set in arr[i]             if ((arr[i] & (1 << j))){                                  countone[j]++;             }         }     }      // For each bit position, compute contribution to Hamming distance     for (int j = 0; j < 32; j++){                  // countone[j] elements have this bit set         // n - countone[j] elements have this bit unset         // Each differing pair contributes 1 to the Hamming distance         count += countone[j] * (n - countone[j]);     }      return count; }  int main(){          vector<int> arr = {4, 14, 4, 14};     int ans = totHammingDist(arr);     cout << ans << endl;       return 0; } 
Java
import java.util.*;  class GfG {          static int totHammingDist(int[] arr) {         int n = arr.length;                       int count = 0;                           int[] countOne = new int[32];                     // Count how many numbers have the j-th bit set         for (int num : arr) {             for (int j = 0; j < 32; j++) {                 // Check if j-th bit is set in the current number                 if ((num & (1 << j)) != 0) {                     countOne[j]++;                 }             }         }          // Calculate Hamming distance contributed by each bit position         for (int j = 0; j < 32; j++) {             // countOne[j] numbers have the j-th bit set             // (n - countOne[j]) numbers have the j-th bit unset             // Each such pair contributes 1 to the Hamming Distance             count += countOne[j] * (n - countOne[j]);         }          // Return the total Hamming Distance         return count;     }      public static void main(String[] args) {                  int[] arr = { 4, 14, 4, 14 };         int ans = totHammingDist(arr);         System.out.println(ans);     } } 
Python
def totHammingDist(arr):     n = len(arr)                         count = 0                            count_one = [0] * 32                      # Count how many numbers have the j-th bit set     for num in arr:         for j in range(32):                      if num & (1 << j):                       count_one[j] += 1         # Calculate total Hamming distance     for j in range(32):         # Each pair where one bit is set and         # the other is not contributes 1 to the distance         count += count_one[j] * (n - count_one[j])      return count   # Driver code if __name__ == "__main__":     arr = [4, 14, 4, 14]                 ans = totHammingDist(arr)            print(ans)   
C#
using System;  class GfG {          // Function to calculate the total Hamming distance between all pairs     static int totHammingDist(int[] arr){                  int n = arr.Length;                          int count = 0;                               int[] countone = new int[32];                         // Count the number of 1s at each bit position for all numbers         for (int i = 0; i < n; i++) {             for (int j = 0; j < 32; j++) {                 // Check if the j-th bit is set in arr[i]                 if ((arr[i] & (1 << j)) != 0) {                     countone[j]++;                 }             }         }          // Calculate the total Hamming distance using bit counts         for (int j = 0; j < 32; j++) {                          // (n - countone[j]) = number of elements with the j-th             // bit not set  Each differing pair at this bit              // position contributes 1 to the Hamming distance             count += countone[j] * (n - countone[j]);         }          return count;     }      // Main method (entry point)     static void Main(){                  int[] arr = { 4, 14, 4, 14 };                int ans = totHammingDist(arr);              Console.WriteLine(ans);              } } 
JavaScript
function totHammingDist(arr){          let n = arr.length;     let count = 0;      // Array to store the count of 1s at each bit position (0 to 31)     let countone = new Array(32).fill(0);      // Count the number of 1s at each bit position for all elements     for (let i = 0; i < n; i++) {         for (let j = 0; j < 32; j++) {                          // Check if the j-th bit is set in arr[i]             if ((arr[i] & (1 << j)) !== 0) {                 countone[j]++;             }         }     }      // Calculate the total Hamming distance     for (let j = 0; j < 32; j++) {          // (n - countone[j]): number of elements where the j-th bit is 0         // Each pair (1, 0) contributes 1 to the Hamming distance         count += countone[j] * (n - countone[j]);     }      return count; }  // Driver Code let arr = [4, 14, 4, 14];                 console.log(totHammingDist(arr));         

Output
8 



Next Article
Total Hamming Distance

A

abhishek5ppd
Improve
Article Tags :
  • Bit Magic
  • DSA
Practice Tags :
  • Bit Magic

Similar Reads

    Concepts of hamming distance
    Hamming Distance Problem: In general, it is assumed that it is more likely to have fewer errors than more errors. This “worst-case” approach to coding is intuitively appealing within itself. Nevertheless, it is closely connected to a simple probabilistic model where errors are introduced into the me
    2 min read
    Hamming Distance between two strings
    You are given two strings of equal length, you have to find the Hamming Distance between these string. Where the Hamming distance between two strings of equal length is the number of positions at which the corresponding character is different. Examples: Input : str1[] = "geeksforgeeks", str2[] = "ge
    4 min read
    Hamming distance between two Integers
    Given two integers, the task is to find the hamming distance between two integers. Hamming Distance between two integers is the number of bits that are different at the same position in both numbers. Examples: Input: n1 = 9, n2 = 14Output: 39 = 1001, 14 = 1110No. of Different bits = 3Input: n1 = 4,
    9 min read
    Minimizing Distance Between Two Walkers
    Given the starting and ending coordinates of path of two persons, the task is to find the minimum distance between the persons at any point of time. The first persons walks from (x1, y1) to (x2, y2) and the second person walks from (x3, y3) to (x4, y4). Both of these persons complete their walks in
    11 min read
    Minimum Distance between Two Points
    You are given an array arr[] of n distinct points in a 2D plane, where each point is represented by its (x, y) coordinates. Find the minimum Euclidean distance between two distinct points.Note: For two points A(px,qx) and B(py,qy) the distance Euclidean between them is:Distance = \sqrt{(p_{x}-q_{x})
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences