Sum of bit differences among all pairs
Last Updated :
23 Jul, 2025
Given an integer array of n integers, find sum of bit differences in all pairs that can be formed from array elements. Bit difference of a pair (x, y) is count of different bits at same positions in binary representations of x and y.
For example, bit difference for 2 and 7 is 2. Binary representation of 2 is 010 and 7 is 111 ( first and last bits differ in two numbers).
Examples :
Input: arr[] = {1, 2}
Output: 4
All pairs in array are (1, 1), (1, 2)
(2, 1), (2, 2)
Sum of bit differences = 0 + 2 +
2 + 0
= 4
Input: arr[] = {1, 3, 5}
Output: 8
All pairs in array are (1, 1), (1, 3), (1, 5)
(3, 1), (3, 3) (3, 5),
(5, 1), (5, 3), (5, 5)
Sum of bit differences = 0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0
= 8
Source: Google Interview Question
Naive Solution:
A Simple Solution is to run two loops to consider all pairs one by one. For every pair, count bit differences. Finally return sum of counts. Time complexity of this solution is O(n2). We are using bitset::count() which is an inbuilt STL in C++ which returns the number of set bits in the binary representation of a number.
C++
// C++ program to compute sum of pairwise bit differences
#include <bits/stdc++.h>
using namespace std;
int sum_bit_diff(vector<int> a)
{
int n = a.size();
int ans = 0;
for (int i = 0; i < n - 1; i++) {
int count = 0;
for (int j = i; j < n; j++) {
// Bitwise and of pair (a[i], a[j])
int x = a[i] & a[j];
// Bitwise or of pair (a[i], a[j])
int y = a[i] | a[j];
bitset<32> b1(x);
bitset<32> b2(y);
// to count set bits in and of two numbers
int r1 = b1.count();
// to count set bits in or of two numbers
int r2 = b2.count();
// Absolute differences at individual bit positions of two
// numbers is contributed by pair (a[i], a[j]) in count
count = abs(r1 - r2);
// each pair adds twice of contributed count
// as both (a, b) and (b, a) are considered
// two separate pairs.
ans = ans + (2 * count);
}
}
return ans;
}
int main()
{
vector<int> nums{ 10, 5 };
int ans = sum_bit_diff(nums);
cout << ans;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
static int sumBitDiff(int[] arr){
int diff = 0; //hold the ans
for(int i=0; i<arr.length; i++){
for(int j=i; j<arr.length; j++){
//XOR toggles the bits and will form a number that will have
//set bits at the places where the numbers bits differ
//eg: 010 ^ 111 = 101...diff of bits = count of 1's = 2
int xor = arr[i]^arr[j];
int count = countSetBits(xor); //Integer.bitCount() can also be used
//when i == j (same numbers) the xor would be 0,
//thus our ans will remain unaffected as (2*0 = 0)
diff += 2*count;
}
}
return diff;
}
//Kernighan algo
static int countSetBits(int n){
int count = 0; // `count` stores the total bits set in `n`
while (n != 0) {
n = n & (n - 1); // clear the least significant bit set
count++;
}
return count;
}
public static void main (String[] args) {
int[] arr = {5,10};
int ans = sumBitDiff(arr);
System.out.println(ans);
}
}
Python3
# Python3 program for the above approach
def sumBitDiff(arr):
diff = 0 #hold the ans
for i in range(len(arr)):
for j in range(i, len(arr)):
# XOR toggles the bits and will form a number that will have
# set bits at the places where the numbers bits differ
# eg: 010 ^ 111 = 101...diff of bits = count of 1's = 2
xor = arr[i]^arr[j]
count = countSetBits(xor) #Integer.bitCount() can also be used
# when i == j (same numbers) the xor would be 0,
# thus our ans will remain unaffected as (2*0 = 0)
diff += (2*count)
return diff
# Kernighan algo
def countSetBits(n):
count = 0 # `count` stores the total bits set in `n`
while (n != 0) :
n = n & (n - 1) # clear the least significant bit set
count += 1
return count
# Driver code
if __name__ == "__main__":
arr = [5,10]
ans = sumBitDiff(arr)
print(ans)
# This code is contributed by sanjoy_62.
C#
/*package whatever //do not write package name here */
using System;
public class GFG {
static int sumBitDiff(int[] arr){
int diff = 0; //hold the ans
for(int i=0; i<arr.Length; i++){
for(int j=i; j<arr.Length; j++){
//XOR toggles the bits and will form a number that will have
//set bits at the places where the numbers bits differ
//eg: 010 ^ 111 = 101...diff of bits = count of 1's = 2
int xor = arr[i]^arr[j];
int count = countSetBits(xor); //int.bitCount() can also be used
//when i == j (same numbers) the xor would be 0,
//thus our ans will remain unaffected as (2*0 = 0)
diff += 2*count;
}
}
return diff;
}
//Kernighan algo
static int countSetBits(int n){
int count = 0; // `count` stores the total bits set in `n`
while (n != 0) {
n = n & (n - 1); // clear the least significant bit set
count++;
}
return count;
}
public static void Main(String[] args) {
int[] arr = {5,10};
int ans = sumBitDiff(arr);
Console.WriteLine(ans);
}
}
// This code contributed by umadevi9616
Javascript
<script>
// javascript program for above approach
function sumBitDiff(arr)
{
let diff = 0;
// hold the ans
for(let i = 0; i < arr.length; i++){
for(let j = i; j < arr.length; j++){
// XOR toggles the bits and will form a number that will have
// set bits at the places where the numbers bits differ
// eg: 010 ^ 111 = 101...diff of bits = count of 1's = 2
let xor = arr[i]^arr[j];
let count = countSetBits(xor);
// Integer.bitCount() can also be used
// when i == j (same numbers) the xor would be 0,
// thus our ans will remain unaffected as (2*0 = 0)
diff += 2*count;
}
}
return diff;
}
// Kernighan algo
function countSetBits(n){
let count = 0; // `count` stores the total bits set in `n`
while (n != 0) {
n = n & (n - 1); // clear the least significant bit set
count++;
}
return count;
}
// Driver code
let arr = [5,10];
let ans = sumBitDiff(arr);
document.write(ans);
// This code is contributed by splevel62.
</script>
Time Complexity: O(n2)
Auxiliary Space: O(1)
Efficient Solution :
An Efficient Solution can solve this problem in O(n) time using the fact that all numbers are represented using 32 bits (or some fixed number of bits). The idea is to count differences at individual bit positions. We traverse from 0 to 31 and count numbers with i'th bit set. Let this count be 'count'. There would be "n-count" numbers with i'th bit not set. So count of differences at i'th bit would be "count * (n-count) * 2", the reason for this formula is as every pair having one element which has set bit at i'th position and second element having unset bit at i'th position contributes exactly 1 to sum, therefore total permutation count will be count*(n-count) and multiply by 2 is due to one more repetition of all this type of pair as per given condition for making pair 1<=i, j<=N.
Below is implementation of above idea.
C++
// C++ program to compute sum of pairwise bit differences
#include <bits/stdc++.h>
using namespace std;
int sumBitDifferences(int arr[], int n)
{
int ans = 0; // Initialize result
// traverse over all bits
for (int i = 0; i < 32; i++) {
// count number of elements with i'th bit set
int count = 0;
for (int j = 0; j < n; j++)
if ((arr[j] & (1 << i)))
count++;
// Add "count * (n - count) * 2" to the answer
ans += (count * (n - count) * 2);
}
return ans;
}
// Driver program
int main()
{
int arr[] = { 1, 3, 5 };
int n = sizeof arr / sizeof arr[0];
cout << sumBitDifferences(arr, n) << endl;
return 0;
}
// This code is contributed by Sania Kumari Gupta (kriSania804)
C
// C program to compute sum of pairwise bit differences
#include <stdio.h>
int sumBitDifferences(int arr[], int n)
{
int ans = 0; // Initialize result
// traverse over all bits
for (int i = 0; i < 32; i++) {
// count number of elements with i'th bit set
int count = 0;
for (int j = 0; j < n; j++)
if ((arr[j] & (1 << i)))
count++;
// Add "count * (n - count) * 2" to the answer
ans += (count * (n - count) * 2);
}
return ans;
}
// Driver program
int main()
{
int arr[] = { 1, 3, 5 };
int n = sizeof arr / sizeof arr[0];
printf("%d\n", sumBitDifferences(arr, n));
return 0;
}
// This code is contributed by Sania Kumari Gupta (kriSania804)
Java
// Java program to compute sum of pairwise
// bit differences
import java.io.*;
class GFG {
static int sumBitDifferences(int arr[], int n)
{
int ans = 0; // Initialize result
// traverse over all bits
for (int i = 0; i < 32; i++) {
// count number of elements with i'th bit set
int count = 0;
for (int j = 0; j < n; j++)
if ((arr[j] & (1 << i)) != 0)
count++;
// Add "count * (n - count) * 2"
// to the answer...(n - count = unset bit count)
ans += (count * (n - count) * 2);
}
return ans;
}
// Driver program
public static void main(String args[])
{
int arr[] = { 1, 3, 5 };
int n = arr.length;
System.out.println(sumBitDifferences(arr, n));
}
}
// This code is contributed by Sania Kumari Gupta (kriSania804)
Python3
# Python program to compute sum of pairwise bit differences
def sumBitDifferences(arr, n):
ans = 0 # Initialize result
# traverse over all bits
for i in range(0, 32):
# count number of elements with i'th bit set
count = 0
for j in range(0, n):
if ( (arr[j] & (1 << i)) ):
count+= 1
# Add "count * (n - count) * 2" to the answer
ans += (count * (n - count) * 2);
return ans
# Driver program
arr = [1, 3, 5]
n = len(arr )
print(sumBitDifferences(arr, n))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to compute sum
// of pairwise bit differences
using System;
class GFG {
static int sumBitDifferences(int[] arr,
int n)
{
int ans = 0; // Initialize result
// traverse over all bits
for (int i = 0; i < 32; i++) {
// count number of elements
// with i'th bit set
int count = 0;
for (int j = 0; j < n; j++)
if ((arr[j] & (1 << i)) != 0)
count++;
// Add "count * (n - count) * 2"
// to the answer
ans += (count * (n - count) * 2);
}
return ans;
}
// Driver Code
public static void Main()
{
int[] arr = { 1, 3, 5 };
int n = arr.Length;
Console.Write(sumBitDifferences(arr, n));
}
}
// This code is contributed by ajit
PHP
<?php
// PHP program to compute sum
// of pairwise bit differences
function sumBitDifferences($arr, $n)
{
// Initialize result
$ans = 0;
// traverse over all bits
for ($i = 0; $i < 32; $i++)
{
// count number of elements
// with i'th bit set
$count = 0;
for ($j = 0; $j < $n; $j++)
if (($arr[$j] & (1 << $i)))
$count++;
// Add "count * (n - count) * 2"
// to the answer
$ans += ($count * ($n -
$count) * 2);
}
return $ans;
}
// Driver Code
$arr = array(1, 3, 5);
$n = sizeof($arr);
echo sumBitDifferences($arr, $n), "\n";
// This code is contributed by m_kit
?>
Javascript
<script>
// Javascript program to compute sum
// of pairwise bit differences
function sumBitDifferences(arr, n)
{
// Initialize result
let ans = 0;
// Traverse over all bits
for(let i = 0; i < 32; i++)
{
// count number of elements with i'th bit set
let count = 0;
for(let j = 0; j < n; j++)
if ((arr[j] & (1 << i)))
count++;
// Add "count * (n - count) * 2" to the answer
ans += (count * (n - count) * 2);
}
return ans;
}
// Driver code
let arr = [ 1, 3, 5 ];
let n = arr.length;
document.write(sumBitDifferences(arr, n));
// This code is contributed by subhammahato348
</script>
Time Complexity: O(n)
Auxiliary Space: O(1)
Thanks to Gaurav Ahirwar for suggesting this solution.
Sum of bit differences | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem