Total Hamming Distance — LeetCode 477 Python Solution

MediumBit ManipulationArrayMath
Problem
#477
Reading time
2 min

The problem

The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.

Example

Input
nums = [4,14,2]
Output
6
Explanation
In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just

Python solution

Python
class Solution:
    def totalHammingDistance(self, nums: List[int]) -> int:
        ans, n = 0, len(nums)
        for i in range(32):
            a = sum(x >> i & 1 for x in nums)
            b = n - a
            ans += a * b
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log M), where n and M are the length of the array and the maximum value in the array, respectively
SpaceO(1) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 477. Total Hamming Distance is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 477. Total Hamming Distance?
LeetCode 477. Total Hamming Distance is rated Medium on LeetCode.
What is the time complexity of LeetCode 477. Total Hamming Distance?
The Python solution on this page runs in O(n \times \log M), where n and M are the length of the array and the maximum value in the array, respectively.
What is the space complexity of LeetCode 477. Total Hamming Distance?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 477. Total Hamming Distance cover?
LeetCode 477. Total Hamming Distance is tagged Bit Manipulation, Array and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview