Bit Manipulation
Work directly with binary: XOR tricks, masks and subsets.
5 pages, free to read
- 1
Binary & bitwise operators
BeginnerEvery integer is a row of bits, and the operators AND, OR, XOR, NOT and shifts let you read, set, clear and flip those bits directly in constant time.
9 min read - 2
XOR tricks
BeginnerBecause x ^ x = 0 and x ^ 0 = x, XOR-ing a list makes every pair cancel out, which finds unique or missing values in O(n) time and O(1) space.
9 min read - 3
Bitmasks for subsets
IntermediateA set of up to about 20 items can be written as one integer where bit i means item i is included, so counting from 0 to 2^n - 1 walks through every subset.
10 min read - 4
Counting & checking bits
Beginnerx & (x - 1) clears the lowest set bit, which gives a fast way to count 1 bits, test for powers of two and reuse earlier answers to count bits for every number up to n.
8 min read - 5
Bitmask DP
AdvancedWhen the state of a DP must remember which of up to about 20 items are already used, store that set as a bitmask, turning n! orderings into about 2^n states.
12 min read