Subsets as Bitmasks
In short: give each of n items a bit position, and every number from 0 to 2ⁿ−1 is a
different subset — bit i is 1 when item i is in it. Counting upward visits every subset
exactly once in O(n · 2ⁿ) time, and set algebra becomes bit operations: union is |,
intersection is &, difference is a & ~b, and membership is a >> i & 1. It's
O(1) extra space per mask, since a whole subset lives in one machine word, so this is a
tool for small n, not for n = 40.

Quarry's query planner has a handful of candidate indexes it could keep in memory: by id, by shard, by epoch, by type. Each costs memory and each speeds up some queries. Which combination should it keep? With a few candidates, the honest answer is to try every combination and keep the best. That's 2ⁿ subsets for n candidates, and this lesson shows the cheapest way to walk them: count.
In the algorithm-design section you generated subsets with backtracking, a recursive
tree of "take it or leave it" choices. Bitmasks flatten that whole tree into a single
for loop over integers. There's no recursion and no call stack, and each subset is
stored in one machine word.
A subset is a number
Give each of the n items a bit position. A subset is then an n-bit number whose bit i
is 1 when item i is in it. Every n-bit number from 0 to 2ⁿ − 1 is a different
subset, and every subset is one of those numbers. Counting upward visits them all:
Counting from 0 to 7 in three bits visits every subset of three indexes exactly once.
mask 0 = 000 selects nothing. That's the empty set, keeping no indexes at all. 3 cells. At index 2.
In code, turning a mask back into items is one comprehension:
mask = 0b1101
print([i for i in range(4) if mask >> i & 1])The cost is the number of masks times the work per mask, O(n · 2ⁿ) to list every subset. That's fine for n = 20, which is about 20 million steps, and impossible for n = 40. Bitmask enumeration is a tool for small n. When n is small, it's often the simplest correct solution there is.
The classic slip is precedence again. This planner should see all 8 subsets:
It prints 4 ['id', 'shard']. Subtraction binds tighter than <<, so the range stops at 1 << 2 and half the subsets never appear.