Skip to content

Commit 88ebb4c

Browse files
committed
added Total Hamming Distance (medium)
1 parent eb928f8 commit 88ebb4c

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
2+
# Total Hamming Distance
3+
[Leetcode Link](https://leetcode.com/problems/total-hamming-distance/)
4+
5+
## Problem:
6+
7+
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different.
8+
9+
Now your job is to find the total Hamming distance between all pairs of the given numbers.
10+
11+
## Example:
12+
13+
```
14+
Input: 4, 14, 2
15+
16+
Output: 6
17+
18+
Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
19+
showing the four bits relevant in this case). So the answer will be:
20+
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
21+
```
22+
23+
## Note:
24+
25+
1. Elements of the given array are in the range of 0 to 10^9
26+
2. Length of the array will not exceed 10^4.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from typing import List
2+
3+
"""
4+
4 => 0100
5+
14 => 1110
6+
2 => 0010
7+
8+
total hamming distance = sum of hamming distance of every bit
9+
hamming distnace of each bit = num of zeros * num of ones (all pairing differences)
10+
"""
11+
def totalHammingDistance(nums: List[int]) -> int:
12+
if not nums:
13+
return 0
14+
total = 0
15+
maxBits = len(bin(max(nums))[2:])
16+
inBinary = [bin(num)[2:].zfill(maxBits) for num in nums]
17+
for j in range(maxBits):
18+
numZeros = 0
19+
for i in range(len(inBinary)):
20+
numZeros += 1 if inBinary[i][j] == '0' else 0
21+
total += numZeros * (len(inBinary)-numZeros)
22+
return total
23+
24+
25+
# test driver
26+
input = [4,14,2]
27+
print("Input:", input)
28+
print("Output:", totalHammingDistance(input))

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ Languages used: Java and Python
3434
- [Design Browser History](Medium/DesignBrowserHistory)
3535
- [Rearrange Words in a Sentence](Medium/RearrangeWordsInSentence)
3636
- [Diagonal Traverse II](Medium/DiagonalTraverse2)
37+
- [Total Hamming Distance](Medium/TotalHammingDistance)
3738
- Hard
3839

3940
---

0 commit comments

Comments
 (0)