Learn / Bit manipulation

Power set

The power set of n items has 2^n subsets, one for every number from 0 to 2^n - 1. Read the bits of each number to decide which items it includes. This gives every subset without recursion.

How to recognise it

  • The question asks for all subsets and n is small (about 20 or less).
  • An iterative method is preferred over recursion.

The idea in one picture

Count in binary from 000 to 111. Each count is a row of yes/no answers for the three items, and every possible row appears exactly once.

maskbits (c b a)subset
0000[]
1001[a]
2010[b]
3011[a, b]
4100[c]
5101[a, c]
6110[b, c]
7111[a, b, c]

Template

for mask from 0 to 2^n - 1:
    subset = items i where bit i of mask is 1
    record subset

Common mistakes

  • Looping to 2^n inclusive, which adds an extra mask with bit n set.
  • Shifting a 32-bit 1 by n ≥ 31.
  • Forgetting the empty subset.

Problems

0 of 1 solved

Check yourself

For items [a, b, c], which subset does the number 6 (binary 110) stand for?

How many numbers does the loop visit for n = 10 items?

What does the number 0 stand for?