← Home

477. Total Hamming Distance

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
477

Let's make this one less mysterious. For 477. Total Hamming Distance, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • TLE
  • 38 / 47 test cases passed.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are count_set_bit, totalHammingDistance.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//TLE
02//38 / 47 test cases passed.
03class Solution {
04public:
05    int count_set_bit(int x){
06        int bits = 0;
07        while(x != 0){
08            bits += x&1;
09            x >>= 1;
10        }
11        return bits;
12    }
13    
14    int totalHammingDistance(vector<int>& nums) {
15        int N = nums.size();
16        
17        int ans = 0;
18        
19        for(int i = 0; i < N-1; i++){
20            for(int j = i+1; j < N; j++){
21                int xorResult = nums[i]^nums[j];
22                ans += count_set_bit(xorResult);
23            }
24        }
25        
26        return ans;
27    }
28};
29
30//iterate from MSB
31//https://leetcode.com/problems/total-hamming-distance/discuss/96226/Java-O(n)-time-O(1)-Space
32//Runtime: 88 ms, faster than 10.31% of C++ online submissions for Total Hamming Distance.
33//Memory Usage: 8 MB, less than 100.00% of C++ online submissions for Total Hamming Distance.
34//time: O(N), space: O(1)
35class Solution {
36public:
37    int totalHammingDistance(vector<int>& nums) {
38        int N = nums.size();
39        
40        int ans = 0;
41        
42        for(int i = 31; i >= 0; i--){
43            int mask = 1 << i;
44            int set = 0, noset = 0;
45            for(int num : nums){
46                if(num & mask){
47                    set++;
48                }else{
49                    noset++;
50                }
51            }
52            ans += set*noset;
53        }
54        
55        return ans;
56    }
57};

Cost

Complexity

Time
O(N), space: O(1)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.