Math Fundamentals18 sections · 814 units
Open in Course

Bitmasks for Subsets

Representing sets as bits

You can represent a subset of nn elements using an integer. Each bit position corresponds to one element: bit ii is 1 if element ii is in the subset, 0 otherwise.

For example, with 4 elements {0,1,2,3}\{0, 1, 2, 3\}, the number 5=01015 = 0101 represents the subset {0,2}\{0, 2\} (bits 0 and 2 are set).

With nn elements, there are 2n2^n possible subsets (each element is either in or out). You can iterate through all subsets by looping from 00 to 2n12^n - 1 and treating each number as a bitmask.