COMPUTER ENGINEER

← BlogDATA STRUCTURES / ALGORITHMSPython example pack ↓

Algorithm design · 38 / 53

Bit masks, bitsets and number theory

Understand → trace → implement → justify

1 min reading · allow extra time for practice

Bit masks encode membership in bit positions. Set with mask|1<<i, test with mask&(1<<i), clear with mask&~(1<<i). Python integers are unbounded; restrict complements explicitly for a fixed-width universe.

x&−x isolates the lowest set bit; x&(x−1) clears it. Submask enumeration uses s=(s−1)&mask and must stop after0. XOR cancels pairs only under the appropriate multiplicity contract.

Bitsets parallelise Boolean work within machine words but large bitsets cost proportional to word count. Euclid computes GCD via remainders, and modular exponentiation follows exponent bits. Modulo and overflow assumptions matter in hashing and arithmetic.

A worked trace

Mask1010₂ represents members1,3; submasks1010,1000,0010,0000 total2^popcount=4.

Cost and assumptions

A b-bit subset universe has2ᵇ states; big-integer bit operations depend on word count.

Executable example

Run with Python 3. Assertions check a small example; they do not constitute a general correctness proof. Some advanced examples are explicitly small models or reference oracles, not full production implementations.

Python 3
def submasks(mask):
    if mask < 0: raise ValueError("nonnegative mask required")
    s=mask
    while True:
        yield s
        if s == 0: break
        s=(s-1)&mask
assert list(submasks(10)) == [10,8,2,0]

TEST YOUR UNDERSTANDING

Your turn

Why is XOR insufficient when other values repeat three times?

Reveal the reasoning

Three XORs leave one copy instead of cancelling. Use bit counts modulo3 or a suitable state machine.

Take it further

  1. Write down the input contract and the invariant before changing the example.
  2. Add empty, boundary, duplicate and adversarial cases where they are relevant. Compare with a simple oracle.
  3. Derive the cost under the stated model; measure several input sizes and explain discrepancies.

Primary reading & lecture notes

Original explanations in this course; these references provide proofs and further reading. Source links may cover the broader module.

MIT 6.046J · Design and Analysis ↗
Solve the exercise before moving on.