Skip to main content
Back to problems
#477
Medium Algorithms

Total hamming distance

Array Math Bit Manipulation
54.6% acceptance
Jan 13, 2026
2301
95
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn total_hamming_distance(nums: Vec<i32>) -> i32 {
    let mut total = 0;
    let n = nums.len();
    
    for bit in 0..32 {
      let ones = nums.iter().filter(|&&num| (num & (1 << bit)) != 0).count();
      total += (ones * (n - ones)) as i32;
    }
    
    total
  }
}