Bit Manipulation
Why Bits Matter
Bit manipulation offers O(1) operations that can replace O(n) loops, enables compact state representation, and unlocks elegant solutions to seemingly complex problems. Analogy: Think of a row of light switches. Each switch is independently on or off—that is a bitmask. Flipping a switch is XOR. Checking if a switch is on is AND. Turning a switch on is OR. Bit manipulation lets you operate on all 32 (or 64) switches simultaneously in a single CPU instruction, which is why it is so fast.Pattern Recognition Signals:
- “XOR” in problem statement → XOR properties
- “Subset” problems with n ≤ 20 → Bitmask DP
- “Toggle/flip” operations → XOR
- “Power of 2” → Bit operations
- “All pairs XOR” → Contribution technique
Essential Bit Operations
Basic Operations
Common Bit Tricks
XOR Properties
XOR is one of the most powerful tools in CP. Understanding its properties deeply is essential for problems rated 1400+. Why XOR is special: Unlike AND and OR, XOR is invertible (you can “undo” it) and self-inverse (applying it twice gives back the original). This makes it perfect for toggling, cancellation, and finding unique elements.Application: Find Single Element
Application: Find Two Missing Numbers
Pattern 1: Bitmask DP (Subsets)
When n ≤ 20, enumerate all 2^n subsets using bitmask. The Idea: Represent a subset as a binary number. If bit i is set, element i is in the subset. Example: For n=4 elements :- mask = 0b1010 = 10 means subset (bits 1 and 3 are set)
- mask = 0b1111 = 15 means all elements
- mask = 0b0000 = 0 means empty set
- mask = which elements have been used/visited
- last = the last element used (for problems where order matters)
Pattern 2: Iterate Over Subsets
Iterating all subsets of a mask: The tricksub = (sub - 1) & mask generates all subsets in decreasing order.
Why it works: Subtracting 1 flips the rightmost 1 and all bits after it. ANDing with mask keeps only valid positions.
Example: mask = 0b1010 (bits 1 and 3)
- Each element is either: not in mask, in mask but not in sub, or in both
- 3 choices per element → 3^n total iterations
Sum Over Subsets (SOS DP)
Compute sum of all subsets for each mask. The Problem: For each mask, compute . Naive: O(3^n). SOS DP: O(n · 2^n). The Insight: Process one bit at a time. After processing bit i, dp[mask] contains the sum over all subsets that may differ from mask only in bits 0 to i. Visual for n=3:Pattern 3: XOR Basis
Find basis vectors for XOR space. The Concept: Any set of numbers can be represented by a “basis”—a minimal set where:- Every number in the original set can be formed by XORing some basis elements
- No basis element can be formed by XORing others
- Basis size ≤ 60 (for 64-bit numbers, at most one element per bit position)
- Maximum XOR = XOR all basis elements with leading bit 1, then greedily add others
- Count of distinct XORs = 2^(basis size)
- For each basis element, try to eliminate its leading bit from x
- If x becomes 0, it was already representable → don’t add
- If x ≠ 0, add it to basis (it brings new information)
Pattern 4: Contribution Technique
Count total XOR sum across all pairs/subsets. The Insight: Instead of iterating over all pairs/subsets (expensive), consider each bit independently and count its contribution. For XOR: A bit contributes to the XOR of a pair only if the two numbers have different values at that bit. Sum of XOR of all pairs:- For each bit position b:
- Count numbers with bit b = 1: call it cnt1
- Count numbers with bit b = 0: call it cnt0 = n - cnt1
- Number of pairs with different bit b: cnt0 × cnt1
- Contribution to total: cnt0 × cnt1 × 2^b
XOR of All Subarray XORs
Pattern 5: Bitmask Operations on Sets
Pattern 6: Gray Code
Generate sequence where consecutive elements differ by exactly 1 bit. Why Gray code matters in CP: Some problems require visiting all 2^n subsets such that each step adds or removes exactly one element. This is exactly what Gray code provides. It also appears in problems about Hamiltonian paths on hypercubes. Hown ^ (n >> 1) works: For any binary number, this formula flips exactly one bit compared to the previous number’s Gray code. The proof relies on the observation that incrementing n in binary flips a contiguous block of bits, and XOR with the right-shifted version “collapses” that block into a single bit flip.
Worked example: n = 3 (8 codes)
Pattern 7: Meet in the Middle with Bitmask
For n up to 40, split into two halves.Common Mistakes
Practice Problems
Beginner (1000-1300)
Intermediate (1300-1600)
Advanced (1600-1900)
Key Takeaways
XOR is Powerful
Self-inverse, associative, and perfect for finding duplicates.
Bitmask for Small N
n ≤ 20: enumerate 2^n states directly.
Bit Contribution
Count each bit’s contribution independently.
Meet in Middle
n ≤ 40: split into two halves of 2^20 each.
Next Up
Chapter 20: Contest Strategy
Master the art of competitive programming contests.