1. 2^n masks
Shifting 1 left by n gives 2^n, the number of subsets.
const total = 1 << nums.lengthTyporithm · medium
Step 1 of 8 · intro card
Bit Manipulation
Each integer mask from 0 to 2^n-1 encodes a subset; bit i decides if nums[i] is included.
There are exactly 2^n subsets, one for every n-bit binary number.
Looping masks from 0 to 2^n-1 enumerates all of them with no recursion.
For each mask, a set bit at position i means the ith element is in that subset.
2^n masks = 2^n subsets.
Bit i selects nums[i].
Iterative, no recursion.
function subsets(nums) {
const result = [];
const total = 1 << nums.length;
for (let mask = 0; mask < total; mask += 1) {
const subset = [];
for (let i = 0; i < nums.length; i += 1) {
if (mask & (1 << i)) {
subset.push(nums[i]);
}
}
result.push(subset);
}
return result;
}Connect each part of the code to the concept before you type.
Shifting 1 left by n gives 2^n, the number of subsets.
const total = 1 << nums.lengthEvery integer from 0 to 2^n-1 encodes one subset.
for (let mask = 0; mask < total; mask += 1)Bit i of the mask decides whether nums[i] is in the subset.
if (mask & (1 << i))A set bit means include the corresponding element.
subset.push(nums[i])Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputValues 1,2,3
Follow temporary values, local state and supporting structures at this step.
Selection mask · high bit first3 bits
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state