Pairwise Sum of Hamming Distance

Given an array ARR containing N integers, your task is to calculate the total sum of the Hamming Distance for all possible pairs of elements in the array.

Hamming Distance

The Hamming Distance between two integers A and B is the number of bits that need to be toggled (changed) in either A or B to make them equal.

Example:

Explanation:
Consider A = 4 and B = 7
Binary representation of 4 = 100
Binary representation of 7 = 111
To convert A to B, flip the last two least significant bits of A to 1.
In this case, you need 2 flips.
Therefore, the Hamming Distance between A and B is 2.

Input:

The first line of input contains an integer T, the number of test cases.
The first line of each test case contains an integer N, the number of elements in the array.
The second line of each test case contains N space-separated integers, representing the array elements.

Output:

For each test case, return the total sum of Hamming Distances for all pairs in the array.

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= 10^4
  • 0 <= ARR[i] <= 10^9
  • Time limit: 1 second

Note:

You are not required to print anything. Just implement the given function to compute the answer.

AnswerBot
4mo

Calculate the total sum of Hamming Distance for all possible pairs of elements in an array.

  • Iterate through all pairs of elements in the array

  • Calculate the Hamming Distance between each pair of element...read more

Help your peers!
Select
Add answer anonymously...
Big Data Analyst Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits