Problem 547309 · medium · Phase 05 Advanced Algorithms & Graphs

Total Disagreement Between Sensor Codes

bit manipulation · counting · Hamming distance

Each sensor reports a code codes[i]. The disagreement of two sensors is the number of bit positions where their codes differ. Return the sum of disagreements over all unordered pairs of sensors.

Examples

Input:  codes = [1, 2, 3]
Output: 4
Explanation: 1 vs 2 differ in 2 bits, 1 vs 3 in 1 bit, 2 vs 3 in 1 bit.
Input:  codes = [7, 0]
Output: 3

Constraints

  • 0 <= len(codes) <= 10**5, 0 <= codes[i] < 2**30.
  • Target complexity: O(30 * n); the O(n^2) pair loop is too slow.

Goals

  • Decompose the pairwise total bit by bit
  • Count pairs that differ in one bit as ones * zeros
  • Avoid the quadratic pair loop
Starting Python…