PrepStack · Markdown HTML

Bitmask subset enumeration

Bit manipulation and bitmask state · HTML

Formal shape

mask ranges over [0,2^n); bit i denotes item i; sub=(sub-1)&mask enumerates nonempty submasks.

Recognition signals

False friends

SignalWhy it is different
Large n2^n becomes infeasible quickly; seek pruning or a different state dimension.
High multiplicities per itemOne bit expresses presence, not a count.

Core invariant

Every mask corresponds to exactly one chosen set, and bit operations faithfully implement set operations.

State, transition, and processing order

ItemDefinition
StateCurrent mask, item list, optional submask, and full-mask boundary.
TransitionIncrement mask for all sets; update a submask with (sub-1)&mask.
Frontier / orderNumeric order is an encoding frontier, not size order; every n-bit code is visited once.

Python skeleton

def all_subsets(items):
    n = len(items)
    for mask in range(1 << n):
        yield [items[i] for i in range(n) if mask >> i & 1]

def nonempty_submasks(mask):
    sub = mask
    while sub:
        yield sub
        sub = (sub - 1) & mask

def is_subset(a, b):
    return a & b == a

Correctness sketch

  1. n-bit strings and subsets of n positions are in bijection.
  2. range(2^n) visits every encoding once.
  3. sub-1 changes the lowest present bit and lower positions; AND with mask removes all outside bits.
  4. The recurrence strictly decreases sub until zero.

Complexity

TimeSpaceParameters
O(2^n n) if every subset is materialized; O(3^n) over all masks and their submasksO(n) for one generated subsetn selectable items

Edge cases

Error patterns

PatternWhy it fails / fix
Dropping the empty setStarting masks at one loses a common base case.
Continuing after sub reaches zeroThe recurrence wraps to mask and loops forever.
Assuming numeric order means size orderAdjacent masks need not have monotone popcount.

Selection and exclusion rules

RelationTemplateBoundary
state skeletonBitmask dynamic programmingMasks enumerate chosen sets
counting alternativeCombinatorial counting / inclusion-exclusionOnly the number of sets is needed
search alternativeSubset / combination backtrackingPruning or path-order generation matters

Original micro-example

PartDetail
ResultMask 5 (binary 101) selects A and C.
ScenarioThree switches A, B, and C.
WalkthroughBits 0 and 2 are set; codes 0 through 7 enumerate all eight configurations.

Recall prompts

My notes