Total Hamming Distance — LeetCode 477 Python Solution
- Problem
- #477
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log M), where n and M are the length of the array and the maximum value in the array, respectively |
| Space | O(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.