ntree.ai
ntree.aiTotal Hamming Distance

Total Hamming Distance

mediumsolvedattempted

The Hamming distance of two integers is the number of bit positions where their bits differ.

Given an integer array nums, return the sum of the Hamming distances over every pair of numbers in it.

Example 1:

Input:  nums = [4, 14, 2]
Output: 6
Explanation: in binary 4 = 0100, 14 = 1110, 2 = 0010. The pairs differ in 2, 2 and 2 positions, so the total is 6.

Example 2:

Input:  nums = [4, 14, 4]
Output: 4

Constraints:

  • 1 <= length of nums <= 10^4
  • 0 <= nums[i] <= 10^9
def totalHammingDistance(nums: list[int]) -> int:
pass
 

Press Visualise to step through your code.