PrepStack · Markdown HTML

Bitwise invariants / XOR cancellation

Bit manipulation and bitmask state · HTML

Formal shape

XOR obeys x^x=0, x^0=x, commutativity, and associativity; AND/OR manage bit sets and (x>>b)&1 reads bit b.

Recognition signals

False friends

SignalWhy it is different
Frequency beyond parity is neededOne XOR retains only parity; use a frequency map or modular bit counts.
Assuming fixed-width negative Python integersPython uses infinite sign extension, so two's-complement tasks need an explicit mask.

Core invariant

The running XOR equals the XOR of values with odd processed frequency; per-bit counts can be reduced independently modulo a repetition count.

State, transition, and processing order

ItemDefinition
StateAn XOR accumulator or W bit counters, plus an explicit full-width mask when needed.
TransitionFor each x, apply acc^=x or add (x>>b)&1 to each bit counter.
Frontier / orderProcessed values are compressed into a bit summary; commutativity makes their internal order irrelevant.

Python skeleton

def single_among_pairs(values):
    ans = 0
    for x in values:
        ans ^= x
    return ans

def hamming_distance(a, b):
    return (a ^ b).bit_count()

def unsigned_low_bits(x, width):
    return x & ((1 << width) - 1)

Correctness sketch

  1. Commutativity and associativity permit arbitrary XOR regrouping.
  2. Each equal pair cancels to zero.
  3. Zero leaves the unpaired value unchanged, so it is the final accumulator.
  4. Set bits of a^b are exactly positions where a and b differ.

Complexity

TimeSpaceParameters
O(n) for XOR aggregation or O(nW) for per-bit countingO(1) or O(W)n values and chosen bit width W

Edge cases

Error patterns

PatternWhy it fails / fix
Treating XOR as additionXOR carries neither arithmetic carries nor magnitude.
Applying a uniqueness trick without its frequency premiseA different repetition pattern leaves a mixture of values.
Ignoring sign extensionRight shifts and complement on negatives must be width-limited.

Selection and exclusion rules

RelationTemplateBoundary
bit-representation extensionBitmask subset enumerationEach bit denotes set membership
higher-information alternativeFrequency table / coordinate countingExact counts are needed
per-bit residueModular arithmetic and fast powerOccurrences cancel modulo k
state encodingPrefix state plus frequency hashThe prefix state is XOR or a parity bitmask.

Original micro-example

PartDetail
ResultThe XOR result is 9.
ScenarioSequence [12,5,12,9,5].
WalkthroughThe two 12s and two 5s cancel independently, leaving 9.

Recall prompts

My notes