Problem 477

Abstract / Summary

Calculate the total number of positions where the binary digits of all numbers differ from each other.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0477.py

class Solution:
    def totalHammingDistance(self, nums: List[int]) -> int:
        size = len(nums)
        bits = [0] * 32
        for n in nums:
            pos = 0
            while n > 0:
                if n & 1:
                    bits[pos] += 1
                pos += 1
                n  >>= 1

        result = 0
        for one in bits:
            zero = size - one
            result += one * zero

        return result
18 lines | 453 bytes | submitted August 19, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The presented Solution class implements a method that computes the total Hamming distance across all unordered pairs of integers in a given list. The Hamming distance between two numbers is defined as the number of bit positions at which the corresponding bits differ. By aggregating these distances for every pair, the method returns a single integer representing the cumulative disparity of the entire collection.

Core Logic

The algorithm relies on the observation that the contribution of each bit position to the total Hamming distance can be calculated independently. For a particular bit index, if k numbers have a 1 at that position and the remaining size-k numbers have a 0, then that bit contributes k * (size-k) to the final sum because each 1 pairs with each 0 exactly once. The implementation therefore performs two passes: the first tallies the count of 1s for each of the 32 possible bit positions, and the second aggregates the contributions using the formula described.

size = len(nums)
bits = [0] * 32

The bits array holds the count of set bits for each position across the entire input.

Bit Counting Loop

The first loop iterates over every number in the input list. For each number, it examines its binary representation from the least-significant bit upward. A right-shift operation discards the already-processed bit, while a bitwise AND with 1 determines whether the current bit is set. When a set bit is encountered, the corresponding entry in bits is incremented. The loop terminates when the shifted value becomes zero, ensuring that only the necessary positions are examined.

for n in nums:
    pos = 0
    while n > 0:
        if n & 1:
            bits[pos] += 1
        pos += 1
        n >>= 1

Pairwise Contribution Calculation

After the bit frequencies have been collected, the second loop computes the total Hamming distance. For each entry in bits, the number of zeros at that position is derived by subtracting the count of ones from the total size of the list. Multiplying the counts of ones and zeros yields the number of differing pairs for that bit, and the result is accumulated into the final answer.

result = 0
for one in bits:
    zero = size - one
    result += one * zero

The method concludes by returning the accumulated result.

Edge Cases Handled

When the input list is empty, size becomes zero, the bits array remains all zeros, and the second loop adds nothing, resulting in a return value of zero. A single-element list also yields zero because there are no pairs to compare; the calculation one * zero evaluates to zero for every bit position. Numbers that are zero contribute no set bits, leaving the corresponding entries in bits unchanged, which correctly reflects that zero has no 1s to affect the distance. The fixed array of length 32 implicitly caps the analysis to 32-bit integers; any higher-order bits beyond this range are ignored, which aligns with typical integer representations in many environments. The loop condition while n > 0 naturally skips processing for non-positive values, treating them as having no set bits for the purpose of this calculation.

Performance Optimizations

The implementation avoids the naïve quadratic approach of examining every pair individually. By collapsing the problem to per-bit counting, it reduces the work to a single linear pass over the input list, followed by a constant-size pass over the 32 bit positions. The use of a pre-allocated list for bits eliminates dynamic resizing overhead. Bitwise operations (& and >>) are employed to extract individual bits efficiently, leveraging the processor’s native support for such operations. The arithmetic in the second loop consists solely of integer multiplication and addition, both of which execute in constant time. Consequently, the method scales gracefully with the size of the input while maintaining a predictable memory footprint.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there is a big collection of numbers. Each number is made up of a string of tiny switches that can be either on or off, just like light switches in a house. This code looks at every single number in the collection one by one. It travels through the switches of each number and keeps a tally of how many switches are turned on for every specific position.

Once the counting is finished, there are thirty-two little buckets, and each bucket holds the total number of switches turned on in that particular spot across all the numbers. To figure out the final answer, the code looks at each bucket. For every position, it multiplies the number of switches that are on by the number of switches that are off. This multiplication tells us how many times a switch is on in one number while being off in another. Adding up all those little multiplication results gives the total distance between all the numbers.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.96 | σ = 0.88

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Rust Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fengvyi C++
fpdjsns C++
fsq C++
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fengvyi C++
fpdjsns C++
fsq C++
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
zfang399 C++
38 links | 24 authors | 9 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

2 easy 6 medium 1 hard
10 solutions   August 19, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality