Typorithm · medium

Subsets via Bitmask

▷ Interactive algorithm labsubsets-bitmaskbit-manipulationbitmaskenumeratemembership
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Subsets via Bitmask

0%

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.

Preparing algorithm lab…
01

2^n masks = 2^n subsets.

02

Bit i selects nums[i].

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. 2^n masks

Shifting 1 left by n gives 2^n, the number of subsets.

const total = 1 << nums.length

2. Each mask

Every integer from 0 to 2^n-1 encodes one subset.

for (let mask = 0; mask < total; mask += 1)

3. Bit i set?

Bit i of the mask decides whether nums[i] is in the subset.

if (mask & (1 << i))

4. Include element

A set bit means include the corresponding element.

subset.push(nums[i])

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Subsets via Bitmask: Visual Walkthrough & Practice · Typorithm | ApplyDjinn