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
| Question | Code |
|---|---|
is item i in m? | (m >> i) & 1 |
add item i | m | (1 << i) |
remove item i | m & ~(1 << i) |
| how many items | popcount of m |
every subset of n items | for m in 0 .. (1 << n) - 1 |
every submask of m | s = 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 << nwithnof 31 or more in 32-bit types. - Forgetting the empty subset (mask 0) when submask loops stop at
s > 0. - Mixing up item
iand bitiwhen items are numbered from 1.
Problems
No problems listed for this pattern yet.