Learn / Bit manipulation

Subsets with bitmasks

A subset of n items can be stored as one integer: bit i is 1 when item i is in. Then 'add item i' is OR, 'is item i in' is AND, the full set is (1 << n) - 1, and looping over all subsets is a plain loop from 0 to 2^n - 1. This makes subsets cheap to store, compare and use as keys in a table.

How to recognise it

  • Items are few (up to about 20) and the state is "which items have been used".
  • A dynamic programming table needs one entry per subset (bitmask DP).
  • You need to visit every subset, or every subset of a given subset.

The idea in one picture

Line up n items and put a light above each one. A subset is a pattern of lights, and a pattern of n lights is just an n-bit number. Counting from 0 to 2^n - 1 shows every pattern exactly once.

Operations

QuestionCode
is item i in m?(m >> i) & 1
add item im | (1 << i)
remove item im & ~(1 << i)
how many itemspopcount of m
every subset of n itemsfor m in 0 .. (1 << n) - 1
every submask of ms = m; while s > 0: …; s = (s - 1) & m (then s = 0)

Where it is used

The Power Set problem in this area lists subsets with this loop. Later, bitmask dynamic programming (for example the travelling salesman problem) stores one table entry per subset of visited items.

Common mistakes

  • Using 1 << n with n of 31 or more in 32-bit types.
  • Forgetting the empty subset (mask 0) when submask loops stop at s > 0.
  • Mixing up item i and bit i when items are numbered from 1.

Problems

No problems listed for this pattern yet.

Check yourself

With 4 items, which mask stands for the subset of items 0 and 2?

How do you loop over every subset of a mask m (its submasks)?

Why are bitmasks limited to small n?