Sum of Bit Difference Among all Pairs

Easy
0/40
Average time to solve is 15m
profile
Contributed by
4 upvotes
Asked in company
Google inc

Problem statement

Given an array of size ‘N’ containing integer elements and let the elements of the given array be 'ARR1', 'ARR2',…..,' ARRN'. You need to find the sum of bit differences among all the pairs that can be formed using the given array elements.

Bit difference of a pair ('ARRi', 'ARRj') is the number of different bits in the numbers’ binary representation. For example, the bit difference of (3,5) is 2. The binary representation of 3 is 011, and of 5 is 101.

Note:
1. If ('ARRi', 'ARRj') is a pair, then ('ARRj', 'ARRi') will also be considered as a pair.
2. Both positive and negative numbers may be present.
3. Don't ignore the negative sign of the number. 
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next 2* T lines represent the ‘T’ test cases. 

The first line of each test case contains an integer ‘N’ denoting the given integer array size.
The second line of each test case contains the ‘N’ space-separated integers denoting the array elements.
Output Format
For each test case, return the sum of bit differences among all the pairs.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 50
1 <= N <= 300
-10^9 <= ARR[i] <= 10^9 

Where ARR[i] is the 'i-th' element of the given array.

Time Limit: 1 sec
Sample Input 1:
2
3
1 2 3
3
1 3 5
Sample Output 1:
8
8
Explanation of Sample Input 1:
Test case 1:
All the pairs in the given array are : (1,1), (1,2), (1,3), (2,1) ,(2,2), (2,3), (3,1), (3,2), (3,3).
Sum of bit differences = 0 + 2 + 1 +2 + 0 + 1 + 1 + 1 + 0 = 8

Test case 2:
All the pairs in the given 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
Sample Input 2:
2
3
5 2 3
3
1 5 9
Sample Output 2:
12
8
Hint

Calculate the bit difference between every pair.

Approaches (2)
Brute Force
  • Run two nested loops to get every pair that can be formed using the given array elements.
  • For each pair calculate the different bits.
Time Complexity

O(N^2), where ‘N’ is the number of elements in the given integer array.

 

We have to run two nested loops to get every pair that can be formed using the given array elements.

Space Complexity

O(1)

 

No extra space is required.

Code Solution
(100% EXP penalty)
Sum of Bit Difference Among all Pairs
Full screen
Console