Subset Enumeration — Bit Manipulation Mastery Guide
⊂ Every subset is an integer. Every integer is a subset.
Welcome, future bit manipulation master! 🚀 Have you ever wondered how to represent ANY possible combination of elements using just a single number? That's exactly what bitmasks do. By the end of this guide, you'll be able to enumerate, filter, and count subsets with blazing-fast bitwise operations.
🤔 Why Subset Enumeration Matters: The Restaurant Menu Problem
Imagine you're at a restaurant with a menu of 10 dishes. You want to order a combination of dishes for the table — any subset of the menu is possible. How many different meal combinations are there? 2¹⁰ = 1024 possibilities!
Now imagine you need to represent each of those 1024 combinations efficiently in a computer program. You could use arrays of booleans, or sets, or hash tables — but what if I told you there's a way to represent ANY subset as a single integer?
That's the power of bitmasks. And the cool part? This isn't just a party trick — problems involving subset enumeration appear in Amazon, Google, Meta, and Microsoft interviews constantly. The "I've seen this before" factor is REAL.
Tip
💡 The Core Insight: An n-bit integer can represent any subset of an n-element set. Bit i being 1 means "element i is included." Iterating from 0 to 2ⁿ − 1enumerates every possible subset exactly once. This is the characteristic vectorrepresentation — set theory implemented in hardware.
Core Concept
1. Bitmask Fundamentals — The Subset↔Integer Connection
Let's build the intuition from the ground up. Forget bitmasks for a moment — think about how you'd represent a subset in everyday life.
🎯 The Big Idea: A Binary Switchboard
Imagine a row of n light switches, each controlling whether a particular element is "in" your set. Switch up (1) = included. Switch down (0) = excluded. That string of 1s and 0s is a binary number. And that binary number is your subset.
All Subsets of a 3-Element Set
For a set of 3 elements [a, b, c] (assigned to bit positions 2, 1, 0), there are 2³ = 8 possible subsets. Each mask from 0 to 7 maps to exactly one subset. Memorize this table — it's the Rosetta Stone of bitmask problems.
🔍 The Extract Pattern — (mask >> i) & 1
This is THE most important bit operation you'll use for subsets. To check whether element at position i is included in a mask:
example.js
function isIncluded(mask, bitPos) {
return (mask >> bitPos) & 1;
}
// Check if element at position 2 is in mask 5 (binary: 101)
isIncluded(5, 2); // → 1 (true — bit 2 is set)
isIncluded(5, 1); // → 0 (false — bit 1 is clear)
isIncluded(5, 0); // → 1 (true — bit 0 is set)
Let's trace (5 >> 1) & 1 step by step:
Step
Expression
Binary
What Happened?
1
5
101
Original mask
2
5 >> 1
010
Shift right — bit 1 moved to position 0
3
010 & 001
000
AND with 1 — only keep lowest bit
4
Result = 0
0
🎯 Bit 1 was 0 — element NOT included
✏️ Setting, Clearing & Toggling Bits
example.js
// Set bit i — turn it ON (add element to subset)
function setBit(mask, i) { return mask | (1 << i); }
// Clear bit i — turn it OFF (remove element from subset)
function clearBit(mask, i) { return mask & ~(1 << i); }
// Toggle bit i — flip membership (XOR)
function toggleBit(mask, i) { return mask ^ (1 << i); }
// Example:
let m = 0b000; // {} — empty set
m = setBit(m, 2); // 100 → {c}
m = setBit(m, 0); // 101 → {a, c}
m = toggleBit(m, 2); // 001 → {a}
m = clearBit(m, 0); // 000 → {}
Note
📝 Memory Aid:| to add (union), & ~ to remove (difference), ^ to toggle (symmetric difference). Each operation has a natural set-theory interpretation!
📋 Bitmask Operations — Quick Reference
Operation
Code
Set Theory
Check bit
(mask >> i) & 1
Is element i in the set?
Set bit
mask | (1 << i)
Add element i
Clear bit
mask & ~(1 << i)
Remove element i
Toggle bit
mask ^ (1 << i)
Flip membership
Empty set
0
No elements
Full set
(1 << n) - 1
All elements
Union
a | b
A ∪ B
Intersection
a & b
A ∩ B
Subset test
(a & b) === a
Is A ⊆ B?
Popcount
bitCount(mask)
How many elements?
Warning
⚠️ JavaScript Bitwise Caveat: Bitwise operations in JS work on 32-bit signed integers. This means bits 0–30 are safe (31 bits for positive values). For n > 31, use BigInt or an array of masks. Most subset enumeration problems have n ≤ 20, so 32 bits is plenty.
Problem 1 & 2
2. Generate All Subsets — The Power Set
LeetCode 78. Subsets: Given an array of distinct integers, return all possible subsets (the power set).
Note
🍕 Real-World Analogy: Imagine you're at a pizza restaurant with n toppings. Every possible combination of toppings is a different pizza. How many different pizzas can you order? 2ⁿ! Each topping is either ON the pizza (1) or OFF the pizza (0). A bitmask is just a binary number where each bit represents one topping. The number 5 (binary 101) means "pepperoni AND olives, but NO mushrooms." Iterating from 0 to 2ⁿ-1 enumerates every possible pizza combination!
🤔 Let's Think About It
Take a moment. If you'd never seen bitmasks, how would you generate all subsets?
Brute Force Approach (Backtracking/DFS)
📋 Edge Cases to Consider
Empty array (n=0): Only one mask (mask=0). Returns [[]]. The empty set is always a valid subset.
Single element (n=1): 2 masks. Returns [[], [x]]. Simple.
n > 31: JavaScript bitwise ops work on 32-bit signed integers. For n > 31, use BigInt or recursion/backtracking.
Array with duplicates (Subsets II): The bitmask approach needs a skip condition to avoid generating duplicate subsets.
example.js
function subsetsBacktrack(nums) {
const result = [];
function dfs(start, path) {
result.push([...path]); // Add current subset
for (let i = start; i < nums.length; i++) {
path.push(nums[i]); // Include element
dfs(i + 1, path); // Recurse
path.pop(); // Backtrack
}
}
dfs(0, []);
return result;
}
// ✅ Works! But uses recursion (call stack O(n))
// Can we do it iteratively?
✅ This works! But recursion means O(n) call stack depth, and we're building subsets one branch at a time. Can we do better?
✨ The Bitmask Solution — Iterative, Branchless
Here's the magic: each mask from 0 to 2ⁿ−1 is a subset. We don't need recursion. We don't need backtracking. Just one loop!
🔍 Real-Time Thinking — What Do I Know?
"I need ALL subsets of n elements. Each element is either included or not — that's a binary choice. For n elements, there are 2ⁿ subsets. If I assign each element a bit position, then every integer from 0 to 2ⁿ-1 represents a unique subset. Mask 0 = empty set. Mask 2ⁿ-1 = full set. To generate the subsets, I just iterate through all masks and check which bits are set. This is branchless, iterative, and uses O(1) auxiliary space for the enumeration itself."
example.js
function subsets(nums) {
const n = nums.length;
const total = 1 << n; // 2^n subsets
const result = [];
for (let mask = 0; mask < total; mask++) {
const subset = [];
// Check every bit position
for (let i = 0; i < n; i++) {
if ((mask >> i) & 1) { // if bit i is set
subset.push(nums[i]); // include element i
}
}
result.push(subset);
}
return result;
}
// subsets([1, 2, 3])
// → [[], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]]
📊 Visualizing the Iteration
Iterate mask from 0 to 2^n minus 1
Each mask from 0 to 2ⁿ − 1corresponds to one subset. The bits of the mask tell you which elements to include. This is the simplest and most elegant subset enumeration pattern.
📊 Dry Run — [1, 2, 3]
mask
binary
bits checked
subset
0
000
—
[]
1
001
bit 0 → nums[0]=1
[1]
2
010
bit 1 → nums[1]=2
[2]
3
011
bits 0,1 → 1,2
[1,2]
4
100
bit 2 → nums[2]=3
[3]
5
101
bits 0,2 → 1,3
[1,3]
6
110
bits 1,2 → 2,3
[2,3]
7
111
bits 0,1,2 → 1,2,3
[1,2,3]
Key Insight
🔑 Pattern: For each mask, we iterate through all n bits. If (mask >> i) & 1 is true, we include nums[i]. The inner loop always runs n times, giving us O(n · 2ⁿ) time — optimal for generating a power set.
📈 Complexity Analysis
Metric
Bitmask Approach
Backtracking (DFS)
Time
O(n · 2ⁿ)
O(n · 2ⁿ)
Space (aux)
O(n) for output buffer
O(n) recursion + O(n) path
Style
Iterative (loop)
Recursive (DFS)
Cache locality
Sequential memory access
Random (tree branches)
🔄 Subsets II — Handling Duplicates
LeetCode 90. Subsets II: Now the array contains duplicates. We must return all unique subsets.
The bitmask approach still works, but we need a skip conditionto avoid generating duplicate subsets. Here's the trick:
example.js
function subsetsWithDup(nums) {
nums.sort((a, b) => a - b); // MUST sort for duplicates to be adjacent
const n = nums.length;
const total = 1 << n;
const result = [];
for (let mask = 0; mask < total; mask++) {
let skip = false;
const subset = [];
for (let i = 0; i < n; i++) {
if ((mask >> i) & 1) {
// Skip if previous is same value AND not taken in this mask
if (i > 0 && nums[i] === nums[i - 1] && !((mask >> (i - 1)) & 1)) {
skip = true;
break;
}
subset.push(nums[i]);
}
}
if (!skip) result.push(subset);
}
return result;
}
// subsetsWithDup([1, 2, 2])
// → [[], [1], [2], [1,2], [2,2], [1,2,2]]
// ✨ Notice: no duplicate subset!
Key Insight
🔑 The Skip Condition Explained: When we encounter a duplicate value at index i, and the previous occurrence (at i−1) is not included in the current mask, we skip. Why? Because the subset without the first occurrence and with the second is identical to the subset with the first occurrence and without the second — but the latter was already generated when the first occurrence was included. This ensures one canonical ordering per unique subset.
Edge Cases
Empty array? Returns [[]] — the only subset is the empty set (mask 0).
Single element? Returns [[], [x]] — 2 subsets.
All duplicates?[1, 1, 1] → only n+1 unique subsets: [[], [1], [1,1], [1,1,1]].
n > 31? Can't use 32-bit bitwise. Use BigInt or recursion.
Tip
⚡ Interview Tip: When you hear "return all possible subsets" in an interview, immediately think bitmasks. Say: "Since each element can be either present or absent, I can represent each subset as a bitmask from 0 to 2ⁿ−1 and iterate." This shows the interviewer you've seen this pattern before.
LeetCode 2044. Count Number of Maximum Bitwise-OR Subsets: Given an array of integers, count the number of non-empty subsets whose bitwise OR equals the maximum possible OR value.
Note
🎯 Real-World Analogy: Imagine a group of friends deciding where to eat. Each person has a list of cuisines they like (their bits). OR-ing them together gives the "master list" of all cuisines anyone likes — that's the maximum possible OR. Any subset of friends that collectively covers ALL cuisines is a "winning" subset. We count how many different groups achieve this!
🤔 Problem Understanding
Let's think about OR for a moment. OR is monotonic — adding more elements to a subset can only set more bits to 1, never clear them. What does this mean?
Key Insight: The maximum possible OR value is simply the OR of ALL elements in the array. The full set contains every bit that any element has. No subset can exceed it.
💭 From Brute Force to Optimal
Brute Force Reasoning
We could enumerate every subset, compute its OR, track the maximum, and count how many subsets achieve it. That's exactly what we'll do — but bitmasks make the enumeration trivial!
✨ The Bitmask Solution
example.js
function countMaxOrSubsets(nums) {
const n = nums.length;
const total = 1 << n;
// Step 1: OR of ALL elements = maximum possible OR
const maxOr = nums.reduce((acc, x) => acc | x, 0);
let count = 0;
// Step 2: Check every non-empty subset
for (let mask = 1; mask < total; mask++) {
let orValue = 0;
for (let i = 0; i < n; i++) {
if ((mask >> i) & 1) {
orValue |= nums[i];
// Early exit: if we already match maxOr, stop
if (orValue === maxOr) break;
}
}
if (orValue === maxOr) count++;
}
return count;
}
// countMaxOrSubsets([3, 1]) → 2 (subsets: {3}, {[3, 1]})
// countMaxOrSubsets([2, 2, 2]) → 7 (all non-empty subsets OR to 2)
// countMaxOrSubsets([3, 2, 1, 5]) → 6
📊 Dry Run — [3, 1]
mask
subset
OR value
Equals maxOr (3)?
01
1
1
❌
10
3
3
✅
11
31
3
✅
Maximum OR = 3 | 1 = 3. Two subsets achieve it: 3 and 31. Answer: 2.
⚡ Optimization — DP Over Masks
We can eliminate the inner loop using DP with bitmasks. The trick: mask & -mask isolates the lowest set bit, and mask ^ lsb removes it, giving us a mask whose OR we already computed!
example.js
function countMaxOrSubsetsDP(nums) {
const n = nums.length;
const total = 1 << n;
const orValues = new Array(total).fill(0);
// DP: build OR values incrementally
for (let mask = 1; mask < total; mask++) {
const lsb = mask & -mask; // lowest set bit
const bitIndex = Math.log2(lsb); // its position
const prevMask = mask ^ lsb; // mask without that bit
// OR of this mask = OR of smaller mask | element at that bit
orValues[mask] = orValues[prevMask] | nums[bitIndex];
}
const maxOr = orValues[total - 1]; // OR of full set
return orValues.filter(v => v === maxOr).length;
}
Key Insight
🔑 The DP Insight: Each mask's OR depends on a mask with one fewer element. This is O(2ⁿ) total — no inner loop! The mask & -mask trick isolates the rightmost 1 bit. Removing it gives us a smaller mask whose OR was already computed. This is the foundation of DP over subsets.
Tip
⚡ Interview Tip: When you see "maximum OR" and "subset" in the same sentence, immediately note that OR is monotonic — the maximum is always the OR of all elements. This is a free observation that shows depth of understanding.
LeetCode 318. Maximum Product of Word Lengths: Given an array of strings, find the maximum product of the lengths of two words that share no common letters.
🔍 Real-Time Thinking — What Do I Know?
"I need to find two words with NO common letters that maximize the product of their lengths. Brute force O(n² × L²) is too slow. But wait — I can encode each word's letters as a 26-bit mask! Then checking if two words share letters becomes a single AND operation: (mask1 & mask2) === 0. That's O(1) instead of O(L²). And I can even deduplicate — if two words have the same mask (same set of letters), I only need to keep the longer one."
🤔 Think About It
The brute force: compare every pair of words (O(n²)), and for each pair, check if they share any letter by scanning both strings (O(L²)). That's O(n² · L²) — painfully slow.
The Bitmask Solution: Encode each word as a 26-bit mask where bit i = 1 means letter ('a' + i) appears in the word. Then checking if two words share letters becomes a single AND operation!
✨ Solution
example.js
function maxProduct(words) {
const n = words.length;
const masks = new Array(n).fill(0);
// Build 26-bit mask for each word
for (let i = 0; i < n; i++) {
let mask = 0;
for (const ch of words[i]) {
mask |= 1 << (ch.charCodeAt(0) - 97); // 'a'→0, 'b'→1, ...
}
masks[i] = mask;
}
let maxProd = 0;
// Compare every pair
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if ((masks[i] & masks[j]) === 0) {
maxProd = Math.max(maxProd, words[i].length * words[j].length);
}
}
}
return maxProd;
}
// maxProduct(["abcw","baz","foo","bar","xtfn","abcdef"])
// → 16 ("abcw" × "xtfn" = 4 × 4)
// maxProduct(["a","ab","abc","d","cd","bcd","abcd"])
// → 4 ("ab" × "cd" = 2 × 2)
26-Bit Letter Masks No Overlap Equals Valid Pair
⚡ Optimization — Mask Deduplication
If multiple words share the same mask (same set of letters), we only need to keep the longest one. A shorter word with identical letters can never beat the longer one's product.
example.js
function maxProductOptimized(words) {
const maskMap = new Map(); // mask → max length
for (const word of words) {
let mask = 0;
for (const ch of word) {
mask |= 1 << (ch.charCodeAt(0) - 97);
}
// Keep only the longest word for each mask
if (!maskMap.has(mask) || word.length > maskMap.get(mask)) {
maskMap.set(mask, word.length);
}
}
const entries = [...maskMap.entries()];
let maxProd = 0;
for (let i = 0; i < entries.length; i++) {
for (let j = i + 1; j < entries.length; j++) {
if ((entries[i][0] & entries[j][0]) === 0) {
maxProd = Math.max(maxProd, entries[i][1] * entries[j][1]);
}
}
}
return maxProd;
}
Tip
⚡ Pro Tip: This optimization is crucial when the input has many anagrams or repeated words. Instead of O(n²) comparisons, we compare only unique masks — typically far fewer than the total word count.
📈 Complexity
Step
Naive
Optimized
Build masks
O(n · L)
O(n · L)
Comparisons
O(n²)
O(m²) where m ≤ n
Total
O(n² + nL)
O(m² + nL)
n = word count, L = average word length, m = distinct masks
LeetCode 784. Letter Case Permutation: Given a string, return all possible strings you can create by toggling the case of each letter independently. Digits remain fixed.
🤔 The Decision: Uppercase or Lowercase?
For each letter in the string, I face a binary choice: "Do I choose uppercase or lowercase?" This is exactly the choose/not-choose framework. Each letter position maps to one bit in a bitmask. If the bit is 1, I choose uppercase. If 0, I choose lowercase. With k letters, I enumerate all 2ᵏ possibilities by iterating masks from 0 to 2ᵏ-1. And with the XOR-32 ASCII trick, toggling case is a single bit flip!
🤔 From Subsets to Case Toggling
This is subset enumeration applied to positions of letters in the string. Each letter can be in one of two states: lowercase or uppercase. If the string has k letters, there are 2k possible case permutations.
The plan:
Find the indices of all letter characters
Let k = number of letters. Enumerate masks from 0 to 2k − 1
For each mask: bit i = 1 → uppercase, bit i = 0 → lowercase
✨ Solution
example.js
function letterCasePermutation(s) {
// Find indices of letter characters
const letterIndices = [];
for (let i = 0; i < s.length; i++) {
if (/[a-zA-Z]/.test(s[i])) {
letterIndices.push(i);
}
}
const k = letterIndices.length;
const total = 1 << k; // 2^k permutations
const result = [];
for (let mask = 0; mask < total; mask++) {
const chars = s.split("");
for (let i = 0; i < k; i++) {
const idx = letterIndices[i];
if ((mask >> i) & 1) {
chars[idx] = chars[idx].toUpperCase();
} else {
chars[idx] = chars[idx].toLowerCase();
}
}
result.push(chars.join(""));
}
return result;
}
// letterCasePermutation("a1b2")
// → ["a1b2", "A1b2", "a1B2", "A1B2"]
// letterCasePermutation("3z4")
// → ["3z4", "3Z4"]
// letterCasePermutation("C")
// → ["c", "C"]
⚡ Bonus: XOR-32 ASCII Trick
Here's a beautiful ASCII trick: lowercase and uppercase letters differ by exactly bit 5 (value 32). XOR with 32 toggles case instantly!
example.js
// 'a' = 97 = 1100001
// 'A' = 65 = 1000001
// Difference is exactly bit 5 (32)
function toggleCase(ch) {
return String.fromCharCode(ch.charCodeAt(0) ^ 32);
}
toggleCase('a'); // → 'A'
toggleCase('Z'); // → 'z'
// Using it in our solution:
function letterCasePermutationFast(s) {
const letterIndices = [];
for (let i = 0; i < s.length; i++) {
if (/[a-zA-Z]/.test(s[i])) {
letterIndices.push(i);
}
}
const k = letterIndices.length;
const total = 1 << k;
const result = [];
const chars = s.split("");
for (let mask = 0; mask < total; mask++) {
// Toggle for each bit set to 1
for (let i = 0; i < k; i++) {
if ((mask >> i) & 1) {
const idx = letterIndices[i];
chars[idx] = String.fromCharCode(chars[idx].charCodeAt(0) ^ 32);
}
}
result.push(chars.join(""));
// Undo the toggles for next mask
for (let i = 0; i < k; i++) {
if ((mask >> i) & 1) {
const idx = letterIndices[i];
chars[idx] = String.fromCharCode(chars[idx].charCodeAt(0) ^ 32);
}
}
}
return result;
}
Key Insight
🔑 ASCII Magic: The XOR-32 trick works because in ASCII, 'A' (65 = 1000001) and 'a' (97 = 1100001) differ only in bit 5. XOR with 32 flips that bit, toggling case. It's perfect for bitmask enumeration because we're already working at the bit level!
Edge Cases
No letters? Returns [s] — the original string unchanged.
All digits? Same as above — only one permutation.
Mixed case input? The solution treats any letter as togglable, regardless of original case.
LeetCode 1915. Number of Wonderful Substrings: A substring is "wonderful" if at most one letter appears an odd number of times. Count substrings that are wonderful.
Note
🔮 Real-World Analogy: Imagine you're watching a light show with 10 colored lights (a through j). Each light can be either ON or OFF. A "wonderful" moment is when at most ONE light has been toggled an odd number of times. As time passes, you track the state (which bulbs are odd-toggled). If you see the same state twice, the substring between those two times has ALL lights toggled even times. If you see a state that differs by one bulb, exactly one light has odd toggles!
🤔 The Hardest Pattern — Parity Prefix XOR
This is the most advanced problem in this guide. Instead of enumerating subsets of array elements, we track the parity (even/odd count) of each letter across prefixes of the string.
Here's the key: if we represent the parity of each letter as a bitmask, then:
Two prefixes with the same parity mask → the substring between them has all even counts
Two prefixes with masks differing by exactly one bit → the substring has exactly one odd count
Since wonderful = at most one letter has odd count, we just need to count prefix pairs that are either identical or differ by one bit!
✨ Solution
example.js
function wonderfulSubstrings(word) {
// 2^10 = 1024 possible parity masks (only letters a-j)
const count = new Array(1024).fill(0);
count[0] = 1; // Empty prefix: all letters even
let prefixMask = 0;
let result = 0;
for (let i = 0; i < word.length; i++) {
const bit = 1 << (word.charCodeAt(i) - 97);
prefixMask ^= bit; // Toggle parity for this letter
// Case 1: substrings with ALL even counts
result += count[prefixMask];
// Case 2: substrings with exactly ONE odd count
for (let b = 0; b < 10; b++) {
result += count[prefixMask ^ (1 << b)];
}
count[prefixMask]++;
}
return result;
}
// wonderfulSubstrings("aba") → 4
// wonderfulSubstrings("aabb") → 9
// wonderfulSubstrings("he") → 2
Wonderful Substrings — Prefix Parity. A substring is wonderful when at most one letter has an odd count. word='aab' => 5 wonderful substrings (not 4).
📊 Dry Run — "aba"
i
char
prefix mask
count[mask] before
add (same)
add (1-bit diff)
result
0
a
001
0
0
0
0
1
b
011
0
0
0
0
2
a
010
1 (match idx 0)
1 ("aa")
0
1
3
a
011
1 (match idx 1)
1 ("aba")
1 ("ba")
3
4
a
010
1 (match idx 2)
1 ("aa")
0
4
For "aba", the four wonderful substrings are "a" at index 0, "b" at index 1, "a" at index 2, and "aba" itself. Each has at most one character whose frequency is odd.
❓ Why 10 Bits?
The problem constrains input to lowercase letters a–j (first 10 letters). So we only need 10 bits — 2¹⁰ = 1024 possible masks, easily fitting in an array.
example.js
// If letters were a-z (26 bits), use Map instead:
function wonderfulSubstringsGeneral(word) {
const count = new Map();
count.set(0, 1); // empty prefix
let prefixMask = 0;
let result = 0;
for (const ch of word) {
prefixMask ^= 1 << (ch.charCodeAt(0) - 97);
// Same mask (all even)
result += count.get(prefixMask) ?? 0;
// 26 possible 1-bit differences
for (let b = 0; b < 26; b++) {
const target = prefixMask ^ (1 << b);
result += count.get(target) ?? 0;
}
count.set(prefixMask, (count.get(prefixMask) ?? 0) + 1);
}
return result;
}
Warning
⚠️ Memory Warning: Never allocate an array of size 2²⁶ = 67 million! For more than ~20 bits, always use a Map. For 10 bits (1024 entries), an array is fast and memory-efficient.
🔗 Why This Is Subset Enumeration
Although this problem doesn't loop over all subsets of the input, it uses the exact same bitmask abstraction — each prefix is a mask encoding the parity of each letter. The inner loop over 10 bits toggling one bit at a time prefixMask ^ (1 << b) is enumerating all masks that differ by one bit from the current prefix — which is a subset enumeration over the 10 possible letters.
Key Insight
🔑 Pattern Recognition: The parity-prefix XOR pattern appears in "Find the Longest Substring with Even Vowel Count" (1371), "Number of Wonderful Substrings" (1915), and other subarray parity problems. The common thread: XOR as subtraction for parity, and a map from mask to first/last occurrence or frequency.
Q1: How do you represent a subset as an integer? Use an n-bit integer where bit i = 1 means element i is included. For a set of size n, integers 0 through 2ⁿ−1 represent all subsets. This is the characteristic vector representation.
Key Insight
Q2: How do you enumerate all subsets with bitmasks? Loop mask from 0 to (1 << n) - 1. For each mask, check every bit position i with (mask >> i) & 1 to extract included elements. Time: O(n · 2ⁿ), space: O(1) auxiliary.
Key Insight
Q3: What's the skip condition for Subsets II (duplicates)? Sort first. When building from a mask, skip if nums[i] === nums[i - 1]and bit (i−1) is 0. This ensures we only take duplicates in one canonical order.
Key Insight
Q4: How do you check if two words share no letters? Encode each as a 26-bit mask (bit = 1 if letter present). Check (maskA & maskB) === 0. If AND is 0, no common letters.
Key Insight
Q5: What is the parity prefix XOR trick? Maintain a prefix mask where bit i = parity of letter i in the prefix. XOR with the letter's bit toggles parity. Two prefixes with the same mask → substring has all even counts. Masks differing by 1 bit → exactly one odd count.
Key Insight
Q6: When should I use an array vs Map for parity counts? Array when mask space ≤ 2²⁰ (~1 million, feasible up to 20 bits). Map for larger spaces (26+ bits). Allocating 2²⁶ (67 million) entries will crash most environments.
Key Insight
Q7: Can I use bitmasks for DP over subsets? Yes! This is called "bitmask DP" or "DP over subsets." The key pattern: compute DP[mask] from DP[mask without one bit] + cost of that element. The mask & -mask trick isolates the lowest set bit to iterate over elements in a mask.
Summary
📝 Key Takeaways
An n-bit integer is a subset — bit i = 1 means element i is included. Iterating 0 to 2ⁿ−1 enumerates the entire power set.
Extract pattern: (mask >> i) & 1 tests membership. Set, clear, and toggle use |, & ~, and ^ with (1 << i).
Subsets II: Sort first, then skip masks where a duplicate is included without its preceding occurrence.
Maximum OR Subsets: OR is monotonic — max OR = OR of all elements. Enumerate and count matches.
Word letter masks: 26-bit encoding turns overlap check into (maskA & maskB) === 0.
Letter Case Permutation: Map each letter position to a bit. Mask decides uppercase (1) vs lowercase (0).
ASCII XOR-32 trick:charCode ^ 32 toggles case instantly — pure bit manipulation.
Wonderful Substrings: Prefix XOR parity mask. Same mask → even counts. One-bit-different → exactly one odd count.
Map for large mask spaces: Array up to ~2²⁰, Map beyond that. Never allocate 2²⁶ entries.
Time: O(n · 2ⁿ), Space: O(1) — bitmask solutions are optimal for subset enumeration problems with n ≤ 20.
Note
🔮 What's Next? Now that you've mastered subset enumeration with bitmasks, head over to AND/OR Range Patternsto learn about range operations, subarray AND/OR, and matrix flipping!