Total Hamming Distance – LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
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 1:
Input: nums = [4,14,2] Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). The answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
Example 2:
Input: nums = [4,14,4] Output: 4
Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 109
- The answer for the given input will fit in a 32-bit integer.
C++ Total Hamming Distance LeetCode Solution
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int size = nums.size();
if(size < 2) return 0;
int ans = 0;
int *zeroOne = new int[2];
while(true)
{
int zeroCount = 0;
zeroOne[0] = 0;
zeroOne[1] = 0;
for(int i = 0; i < nums.size(); i++)
{
if(nums[i] == 0) zeroCount++;
zeroOne[nums[i] % 2]++;
nums[i] = nums[i] >> 1;
}
ans += zeroOne[0] * zeroOne[1];
if(zeroCount == nums.size()) return ans;
}
}
};
Java Total Hamming Distance LeetCode Solution
public int totalHammingDistance(int[] nums) {
int total = 0, n = nums.length;
for (int j=0;j<32;j++) {
int bitCount = 0;
for (int i=0;i<n;i++)
bitCount += (nums[i] >> j) & 1;
total += bitCount*(n - bitCount);
}
return total;
}
Python 3 Total Hamming Distance LeetCode Solution
def totalHammingDistance(self, nums):
return sum(b.count('0') * b.count('1') for b in zip(*map('{:032b}'.format, nums)))
Array-1180
String-562
Hash Table-412
Dynamic Programming-390
Math-368
Sorting-264
Greedy-257
Depth-First Search-256
Database-215
Breadth-First Search-200
Tree-195
Binary Search-191
Matrix-176
Binary Tree-160
Two Pointers-151
Bit Manipulation-140
Stack-133
Heap (Priority Queue)-117
Design-116
Graph-108
Simulation-103
Prefix Sum-96
Backtracking-92
Counting-86
Sliding Window-73
Linked List-69
Union Find-66
Ordered Set-48
Monotonic Stack-47
Recursion-43
Trie-41
Binary Search Tree-40
Divide and Conquer-40
Enumeration-39
Bitmask-37
Queue-33
Memoization-32
Topological Sort-31
Geometry-30
Segment Tree-27
Game Theory-24
Hash Function-24
Binary Indexed Tree-21
Interactive-18
Data Stream-17
String Matching-17
Rolling Hash-17
Shortest Path-16
Number Theory-16
Combinatorics-15
Randomized-12
Monotonic Queue-9
Iterator-9
Merge Sort-9
Concurrency-9
Doubly-Linked List-8
Brainteaser-8
Probability and Statistics-7
Quickselect-7
Bucket Sort-6
Suffix Array-6
Minimum Spanning Tree-5
Counting Sort-5
Shell-4
Line Sweep-4
Reservoir Sampling-4
Eulerian Circuit-3
Radix Sort-3
Strongly Connected Componen-t2
Rejection Sampling-2
Biconnected Component-1