Bitmasks: every subset as a number

Video lessonComing soon

1 A subset is a row of switches

A pizza shop offers three toppings: paneer, onion and corn. A customer can pick any of them, all three, or none. We want a program that lists every pizza they could order.

For three toppings, three nested loops would work. But a problem gives us n items, and n changes from one input to the next. We cannot write n nested loops, so we need one loop that walks through every choice.

A choice of items is a subset. We can draw it as a row of switches, one per topping. A switch that is on puts that topping on the pizza.

1corn0onion1paneerbit 2bit 1bit 0
Paneer and corn on, onion off: the switches read 101

A row of 0s and 1s is a number in binary. Here 101 is 4 + 1 = 5, so this pizza is the number 5.

A number used this way is a bitmask, or a mask for short. Bit i of the mask is the switch for item i. Bit 0 is the rightmost one, so paneer, item 0, sits on the right.

2 Counting from 0 to 2ⁿ − 1 visits every subset

Three switches, each on or off, give 2 × 2 × 2 = 8 pizzas. Three bits also write exactly 8 numbers, from 000 to 111, which is 0 to 7. Each pizza has one row of switches, and each row is one number. So counting from 0 to 7 visits every pizza exactly once.

maskbinarytoppings
0000none
1001paneer
2010onion
3011paneer, onion
4100corn
5101paneer, corn
6110onion, corn
7111paneer, onion, corn

The steps below build the same list one topping at a time, with P for paneer, O for onion and C for corn. Each new topping is a new bit on the left. The masks with that bit off are the pizzas we already had. The masks with it on are the same pizzas with the new topping added.

Each new item doubles the list
none0P1     2     3     4     5     6     7
Paneer is bit 0. Masks 0 and 1 are the pizza without it and with it

Every item doubles the count, so n items give 2ⁿ subsets. Their masks are the numbers 0 to 2ⁿ − 1. In code, 2ⁿ is 1 << n: a 1 shifted n places to the left.

3 Is item i in the mask?

To turn a mask back into a pizza, we ask each switch in turn: is bit i on?

The number 1 << i has a single 1, at bit i. It works like a stencil with one hole. ANDing the mask with it keeps that one switch and clears all the others. The result is 0 when the switch is off, and not 0 when it is on.

Reading mask 5, which is 101, one bit at a time
1corn0onion1paneer
mask = 5
0corn0onion1paneer
1 << 0
0corn0onion1paneer
AND is 1, not 0: paneer is in
item i is in the mask exactly when (mask & (1 << i)) != 0

The test is "not 0", never "equals 1". When corn's bit is on, the AND gives 4, the value of bit 2.

4 Building every subset

Now the loop writes itself. The outer loop counts mask from 0 to 2ⁿ − 1. For each mask, an inner loop reads bits 0 to n − 1 and collects the items whose bit is on.

Here is the inner loop for mask 6, which is 110:

iitems[i]1 << imask & (1 << i)subset
0paneer001000[]
1onion010010[onion]
2corn100100[onion, corn]

The loop reads bits from 0 up, so each subset keeps the items in their original order. On the three toppings, every tab returns the 8 pizzas of the table in section 2, in the same order.

There are 2ⁿ masks, and each one reads n bits, so the time is O(n · 2ⁿ). Each item is in half of the subsets, so the answer holds about n · 2ⁿ / 2 items, and it needs that much space.

This is one way to list all subsets. A later lesson, on the pick-or-skip tree, builds the same subsets with recursion.

5 Set operations are bit operations

A mask holds a whole set in one number. So the questions we ask about sets become single bit operations, and each one is O(1).

Two friends order. Asha wants paneer and corn, which is 101. Ravi wants onion and corn, which is 110.

1corn0onion1paneer
asha = 5
1corn1onion0paneer
ravi = 6
Set questionBit operationWith Asha and Ravi
Toppings either one wants (union)a | b111
Toppings both want (intersection)a & b100, only corn
Add item ia | (1 << i)add onion: 111
Remove item ia & ~(1 << i)remove corn: 001
Flip item ia ^ (1 << i)flip paneer: 100
Every item(1 << n) - 1111
Items a does not havea ^ every010, only onion
How many itemscount the 1 bits2

Add, remove and flip are the set, clear and toggle from the last lesson, now read as changes to an order. Counting the 1 bits of a number is its popcount.

C++

Popcount for 64 bits. __builtin_popcount takes an int. For a long long mask, use __builtin_popcountll.

Popcount for 64 bits. Integer.bitCount takes an int. For a long mask, use Long.bitCount.

Older Python. bit_count() needs Python 3.10 or newer. On older versions, bin(asha).count("1") gives the same count.

No built-in popcount. JavaScript has none, so we write the short loop above. It moves the mask right one bit at a time and adds up the bits it sees.

NOT is ^x in Go. Go has no ~. To clear bits, it has its own operator: a &^ b clears from a every bit that is set in b. OnesCount comes from the math/bits package.

NOT is !x in Rust. Rust has no ~. On a number, ! flips every bit. count_ones() works on every integer type.

Popcount needs a cast. BitOperations.PopCount comes from System.Numerics and takes a uint or a ulong, so we cast the mask first.

6 Every subset of one mask

Some problems start from one set and need every part of it. Asha's order 101 holds four orders: 101, 100, 001 and 000. These are its submasks. Checking every number below 101 works, but it wastes steps when the mask has few bits on.

One line jumps from each submask straight to the next smaller one:

sub = (sub − 1) & mask

Subtracting 1 turns the lowest 1 of sub into 0, and every bit below it into 1. The AND with mask then clears the bits Asha never picked. The result is the next smaller number that uses only her toppings.

From 100 to the next submask of 101
1corn0onion1paneer
mask = 101
1corn0onion0paneer
sub = 100: corn alone

Counting down from 100 would pass 011 and 010, which both hold onion. The AND skips them in one step. The whole walk from 101 takes three jumps:

subsub − 1(sub − 1) & 101
101100100
100011001
001000000
000stop

For mask 5, every tab returns 5, 4, 1 and 0. The loop adds sub before it checks for 0, so the empty set is included, and the loop stops right after it. A mask with k bits on has 2ᵏ submasks, so the loop takes O(2ᵏ) steps, not 2ⁿ.

7 Mistakes and edge cases

  • Comparing with 1. (mask & (1 << i)) == 1 is true only for bit 0, because bit i gives 2ⁱ. On the toppings, onion and corn are never picked, and no subset holds more than paneer.
  • Stopping one short. With mask < (1 << n) - 1, the loop never reaches 111, so the subset with every item is missing.
  • Ending the submask loop wrong. With while (sub > 0), the loop stops before the empty set, so mask 5 gives only 5, 4 and 1. With while (sub >= 0), it never stops, because (0 − 1) & 5 is 5 again and the walk starts over.
  • Too many items for the mask. A 32-bit int holds bits 0 to 31. The letters of a word fit, but a set drawn from 40 kinds of things needs a 64-bit mask, and a 64-bit 1 in 1 << i.

C++

Past 31 items. 1 << 32 on an int is undefined. Keep the mask in a long long and write 1LL << i.

Past 31 items. 1 << 32 gives 1, because Java uses only the last 5 bits of the shift count. Use a long mask and 1L << i.

No limit. Python's integers have no fixed width, so 1 << 100 is fine.

Past 31 items. Bit operators work on 32 bits: 1 << 31 is −2147483648 and 1 << 32 is 1. Use BigInt, as in 1n << 40n.

Up to 62 items. int is 64 bits, so 1 << i is fine without any change.

Past 32 items. Shifting a u32 by 32 or more is an overflow. Use a u64 mask.

Past 31 items. 1 << 32 gives 1, because C# uses only the last 5 bits of the shift count. Use a long mask and 1L << i.

8 When n is small enough

Listing every subset costs about n · 2ⁿ steps, and 2ⁿ doubles with every item. The chart shows where that crosses the time limit:

n = 1010⁴n = 202 × 10⁷n = 258 × 10⁸n = 303 × 10¹⁰about 1 second
n · 2ⁿ steps, on a scale where each mark is ten times the last

At n = 20 it is around 2 × 10⁷ steps, well inside the limit. At n = 30 it is around 3 × 10¹⁰. At about 10⁸ steps a second, that is far past the time limit, so it gets TLE. So a mask loop over every subset fits when n is about 20 or less.

The signs to look for:

  • Try every choice. The problem asks for the best, the count or the list of the subsets of a few items, and n is at most about 20.
  • A small set as one value. A set drawn from few kinds of things fits in one number. The letters of a word fit in 26 bits, and two words share a letter exactly when their masks AND to something other than 0.
When n is 20 or less and the problem is about choosing items, picture each item as a switch. Then count the steps for all 2ⁿ masks before writing the loop.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.