Typorithm · medium

Subsets

▷ Interactive algorithm labsubsetsbacktrackingpower-setchoose-explore-undostart-index
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Subsets

0%

Backtracking

Build the power set by recording every node of a choose / explore / undo recursion tree.

Every subset corresponds to a node in a recursion tree that grows by adding one later element at a time.

A start index ensures each element is only ever extended forward, so no subset repeats.

Push to choose, recurse to explore, then pop to undo — the universal backtracking shape.

Preparing algorithm lab…
01

Record the path at every node.

02

Loop from start to avoid duplicates.

03

Choose, recurse, then undo.

function subsets(nums) {
  const result = [];

  function backtrack(start, path) {
    result.push([...path]);

    for (let i = start; i < nums.length; i += 1) {
      path.push(nums[i]);
      backtrack(i + 1, path);
      path.pop();
    }
  }

  backtrack(0, []);
  return result;
}

Read the implementation

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

1. Record node

Every node of the recursion tree is itself a valid subset.

result.push([...path])

2. Choices from start

Starting at start avoids reusing earlier elements and duplicate subsets.

for (let i = start; i < nums.length; i += 1)

3. Choose

Add the current element to the path.

path.push(nums[i])

4. Explore

Recurse with the next start so each element is used at most once.

backtrack(i + 1, path)

5. Undo

Remove the element to restore state for the next choice.

path.pop()

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: Visual Walkthrough & Practice · Typorithm | ApplyDjinn