← Back to Algorithms, page 5

algorithms-0100 · Easy fresher

Hamming distance and reversing bits: count the bit positions where two integers differ, sum that over all pairs efficiently, and reverse the bits of a 32-bit unsigned integer.

The Hamming distance of a and b is the popcount of a XOR b. Summing over all pairs one pair at a time is O(n^2), but per bit position the number of differing pairs is ones times zeros, which gives O(32n). Reversing bits shifts the result left and moves in x's lowest bit 32 times.

Full answer

Problem

  1. Return the number of positions where the bits of a and b differ.
  2. Return the sum of Hamming distances over all pairs in nums.
  3. Reverse the bits of a 32-bit unsigned integer.

Example: hamming(1, 4) = 2 (001 versus 100). For [4, 14, 2] the total is 6 (2 + 2 + 2). Reversing 00000010100101000001111010011100 gives 00111001011110000010100101000000, which is 964176192.

Constraints: values are 32-bit unsigned (0 to 2^32 - 1); up to 10^4 numbers for the total.

Brute force

Compare bit strings character by character for each pair: O(32) per pair and O(32 n^2) for all pairs. Reversing by converting to a padded 32-character string and reversing it works but allocates strings.

Optimal approach

  • Hamming distance: x = a ^ b, then count set bits with x &= x - 1.
  • Total over pairs: for each bit b in 0..31, let ones be how many numbers have bit b set; add ones * (n - ones).
  • Reverse bits: out = 0; repeat 32 times: out = (out << 1) | (x & 1), x >>= 1.

Why it works

XOR leaves a 1 exactly where the two inputs differ, so its popcount is the distance. For the total, each bit position contributes independently: a pair differs at bit b exactly when one number has a 1 there and the other a 0, and there are ones * zeros such pairs. Reversal moves the lowest bit of x into the result and shifts earlier bits up, so after 32 steps bit i has moved to position 31 - i.

Complexity

Hamming distance: O(number of set bits). Total: O(32n) time, O(1) space. Reverse bits: O(32). For many reverse calls, a 256-entry lookup table reverses a byte at a time.

Code

python
import random


def hamming_distance(a, b):
    """Number of bit positions that differ: popcount of a XOR b."""
    x, n = a ^ b, 0
    while x:
        x &= x - 1
        n += 1
    return n


def total_hamming(nums):
    """Sum over all pairs in O(32 * n): at each bit, ones * zeros pairs differ."""
    total, n = 0, len(nums)
    for b in range(32):
        ones = sum((v >> b) & 1 for v in nums)
        total += ones * (n - ones)
    return total


def reverse_bits(x):
    """Reverse a 32-bit unsigned integer."""
    out = 0
    for _ in range(32):
        out = (out << 1) | (x & 1)
        x >>= 1
    return out


def brute_total(nums):
    return sum(hamming_distance(nums[i], nums[j]) for i in range(len(nums)) for j in range(i + 1, len(nums)))


if __name__ == "__main__":
    assert hamming_distance(1, 4) == 2 and hamming_distance(3, 1) == 1 and hamming_distance(7, 7) == 0
    assert total_hamming([4, 14, 2]) == 6
    assert reverse_bits(0b00000010100101000001111010011100) == 964176192
    assert reverse_bits(1) == 1 << 31 and reverse_bits(0) == 0
    rng = random.Random(100)
    for _ in range(500):
        nums = [rng.randint(0, (1 << 32) - 1) for _ in range(rng.randint(0, 12))]
        assert total_hamming(nums) == brute_total(nums)
        v = rng.randint(0, (1 << 32) - 1)
        assert reverse_bits(v) == int(format(v, "032b")[::-1], 2)
        assert reverse_bits(reverse_bits(v)) == v
    print("all tests passed")

Save as b100_hamming_reverse_bits.py and run python3 b100_hamming_reverse_bits.py. It prints all tests passed (Python 3.13.5).

Edge cases

Equal numbers (distance 0). Zero and the maximum 32-bit value. Reversal of 1 is 1 << 31. Fewer than two numbers (total 0). In fixed-width languages, use unsigned shifts (>>> in Java) so the sign bit is not copied.

Pattern

XOR to find differences, and per-bit counting to turn an O(n^2) pair sum into O(32n). Related: sum of XOR over all pairs, maximum XOR pair (binary trie), and error-detecting codes that rely on Hamming distance.

python
import random


def hamming_distance(a, b):
    """Number of bit positions that differ: popcount of a XOR b."""
    x, n = a ^ b, 0
    while x:
        x &= x - 1
        n += 1
    return n


def total_hamming(nums):
    """Sum over all pairs in O(32 * n): at each bit, ones * zeros pairs differ."""
    total, n = 0, len(nums)
    for b in range(32):
        ones = sum((v >> b) & 1 for v in nums)
        total += ones * (n - ones)
    return total


def reverse_bits(x):
    """Reverse a 32-bit unsigned integer."""
    out = 0
    for _ in range(32):
        out = (out << 1) | (x & 1)
        x >>= 1
    return out


def brute_total(nums):
    return sum(hamming_distance(nums[i], nums[j]) for i in range(len(nums)) for j in range(i + 1, len(nums)))


if __name__ == "__main__":
    assert hamming_distance(1, 4) == 2 and hamming_distance(3, 1) == 1 and hamming_distance(7, 7) == 0
    assert total_hamming([4, 14, 2]) == 6
    assert reverse_bits(0b00000010100101000001111010011100) == 964176192
    assert reverse_bits(1) == 1 << 31 and reverse_bits(0) == 0
    rng = random.Random(100)
    for _ in range(500):
        nums = [rng.randint(0, (1 << 32) - 1) for _ in range(rng.randint(0, 12))]
        assert total_hamming(nums) == brute_total(nums)
        v = rng.randint(0, (1 << 32) - 1)
        assert reverse_bits(v) == int(format(v, "032b")[::-1], 2)
        assert reverse_bits(reverse_bits(v)) == v
    print("all tests passed")

Kernighan popcount over XOR, per-bit total over pairs, and 32-step reversal, cross-checked against pairwise sums and string reversal.

Complexity

Time: O(32n) for the pair total; O(32) for reversal. Space: O(1). A byte lookup table reduces reversal to 4 lookups.

By level

Fresher: Computes the distance with XOR and a bit count, and reverses bits with a loop of 32 shifts. Traces both on small values.

Mid: Turns the pair sum into per-bit counts and explains why bit positions are independent. Handles unsigned behaviour across languages.

Senior: Discusses lookup tables and hardware instructions for bit reversal and popcount, and uses of Hamming distance in error-correcting codes and similarity hashing. Explains how SimHash fingerprints use it to find near-duplicate documents.

Key points

  • Distance = popcount(a XOR b)
  • Per bit, differing pairs = ones * zeros
  • Pair total in O(32n)
  • Reverse by shifting in the lowest bit 32 times
  • Use unsigned shifts in fixed-width languages

Common mistakes

  • Summing pairs directly in O(n^2)
  • Reversing only the significant bits instead of all 32
  • Using signed shifts in Java or C
  • Forgetting that Python integers are unbounded when emulating 32-bit values

Follow-ups

  • How would you speed up reversal for millions of calls?
  • How do you find the pair with the maximum XOR?
  • Where is Hamming distance used in practice?

Tips

  • Show XOR on two small numbers
  • Explain the ones * zeros count
  • Mention lookup tables for repeated reversal

Evaluation rubric

  • Correct distance
  • O(32n) pair total
  • Correct 32-bit reversal
  • Edge cases