Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Backtracking

Push, Recurse, Pop.

Don't memorize backtracking — watch the decision tree grow and unwind. To list every subset of a set, treat each element as a choice: take it or skip it. Every node you land on is a subset, and the moment a branch runs out you pop the last choice and try the next. That push-recurse-pop rhythm is the whole of backtracking — the engine behind subsets, permutations, N-Queens and Sudoku.

decision tree · every node is a subset · pop to undo · 2ⁿ leaves
BACKTRACK

Build a choice step by step; undo the last step when the branch is done.

DECISION TREE

At each element you branch: include it, or move past it. A tree of partial answers.

EVERY NODE COUNTS

For subsets, each node you visit is itself a valid subset — record it.

POP TO UNDO

After a branch, remove the last element (path.pop()) and try the next candidate.

subsets.sim — all subsets of {1, 2, 3}
Ready

Each node is a subset. From a node you branch to add the next larger element. Press Step to walk the tree depth-first — every node visited is recorded, and finishing a branch pops back to try the next.

bt(start, path): record path; for i in start..n: push, bt(i+1), pop
0
Subsets found
∅
Current path

The tree is the algorithm

Backtracking is just depth-first search over a tree you never actually build — you generate it on the fly with the call stack. For subsets, the rule at each step is: from the current position, pick the next element to include, recurse on everything after it, then remove it. That moving start index is the key detail: by only ever looking forward, you generate each subset once, in a tidy order, and never produce a reshuffle of one you already have. Every recursive call corresponds to a node, and because a subset is the path from the root, you record the path at the top of every call. Two-to-the-n nodes, two-to-the-n subsets.

01

Record the node

At the start of each call, the current path is a complete subset — push a copy into the results.

02

Branch forward

Loop i from start to n−1: choose to include element i by pushing it onto the path.

03

Recurse deeper

Call bt(i + 1, path) — later choices can only use elements after i, so no duplicates.

04

Pop and continue

path.pop() undoes the choice; the loop moves to the next i. That pop is the backtrack.

Subsets
2ⁿ
Time
O(n · 2ⁿ)
Space
O(n)
Pattern
Backtracking

Change only the branching rule and the same skeleton solves a whole family of problems. Place every remaining element in the next slot and you get permutations (n! of them). Add a constraint check before recursing — no two queens attacking, a legal Sudoku digit, a running sum that has not overshot a target — and you get N-Queens, Sudoku, combination sum. The wins come from pruning: cut a branch the instant it cannot lead to a solution, and the 2ⁿ or n! blow-up shrinks dramatically.

Check yourself

1 · How many subsets does a set of n elements have?

Every element is a yes/no choice, so there are 2 × 2 × … = 2ⁿ subsets, including the empty set and the full set.

2 · In backtracking, what does the "backtrack" step actually do?

After exploring a branch you pop the last element off the path, returning to the parent state so the next candidate can be tried.

3 · Why recurse with a moving start index (i + 1)?

Only looking forward means {1,2} is generated but never {2,1}; subsets are order-free, so this avoids duplicates.

The picture: the tree is the call stack

1{}2{1}3{1, 2}4{1, 2, 3}5{1, 3}6{2}7{2, 3}8{3}The call stack is the path:depth 0 → 3 is three pushes,then three pops walk back up.8 nodes = 2³ subsetsnumbers: visit order
Visit order for {1, 2, 3}, indented by recursion depth. Each node is the path at the top of a call, and each is recorded. The deepest node, {1, 2, 3}, is visited fourth; after it the recursion pops back to {1} and takes the next branch, {1, 3}.

Worked example, step by step

Run backtrack(start) on nums = [1, 2, 3]. Each row is one call recording its path on entry. The last column is what that call and the ones above it undo (pop) before the next call begins.

#CallDepthPath recordedPops before next record
1bt(0)0{}—
2bt(1)1{1}—
3bt(2)2{1, 2}—
4bt(3)3{1, 2, 3}pop 3, pop 2
5bt(3)2{1, 3}pop 3, pop 1
6bt(2)1{2}—
7bt(3)2{2, 3}pop 3, pop 2
8bt(3)1{3}pop 3

Two things stand out. The start index only grows, so {1, 3} exists but {3, 1} never appears: every subset comes out once, in a fixed order, without a seen-set. And the pops are not a clean-up step: after row 4 the code pops 3, then 2, because both loops are exhausted, and only then does i advance to 3 under {1}. Without the pop, the path would still hold 2 when 3 was pushed, and row 5 would read {1, 2, 3, 3}. Eight rows, 12 elements copied into the result in total (an average of 1.5 per subset), which is where the extra factor of n in the cost comes from.

Complexity and trade-offs

CaseTimeSpaceWhy
Backtracking with start indexO(n·2ⁿ)O(n) extra2ⁿ nodes, each copying a path of average length n/2. Stack depth and path are at most n; the result itself is larger.
Bitmask loopO(n·2ⁿ)O(1) extraFor mask in 0…2ⁿ−1, emit the elements whose bit is set. No recursion, but limited to n ≤ 62 and no pruning.
Cascading (append x to every existing subset)O(n·2ⁿ)O(n·2ⁿ)Builds iteratively and holds the whole list in memory as it goes. Same output, same cost, no stack.
Backtracking with pruningO(2ⁿ) worst caseO(n)Add a feasibility test before recursing (a sum limit, a conflict) and whole subtrees vanish. The worst case is unchanged; typical cases are far smaller.

No method can beat n·2ⁿ for “return every subset”, because the output holds n·2ⁿ⁻¹ elements: 12 for n = 3, 5,120 for n = 10, over ten million for n = 20. Only a task that does not need the whole list (count, search for one valid subset, stop at the first hit) can do better, and that is exactly where backtracking’s ability to prune and stop early pays off while the bitmask loop cannot.

Common mistakes

  • Appending the path itself instead of a copy

    result.append(path) stores a reference. The path is emptied by the pops, so every entry ends up pointing at the same empty list: for [1, 2, 3] the result is eight empty lists. Append path[:] (or list(path)).

  • Forgetting to pop

    Without path.pop() the choices pile up and leak into sibling branches. On [1, 2, 3] the output becomes {} {1} {1, 2} {1, 2, 3} {1, 2, 3, 3} … and its last entry has seven elements from a three-element input.

  • Duplicates in the input

    On [1, 2, 2] the plain algorithm returns 8 subsets, listing {1, 2} and {2} twice. Sort first and skip i when i > start and nums[i] == nums[i-1]; that gives the correct 6.

  • Recording only at the leaves

    In permutations a full-length path is the answer. In subsets every node is an answer. Recording only when start == n returns 4 of 8: {1, 2, 3} {1, 3} {2, 3} {3}. Record at the top of every call.

  • Looping from 0 instead of start

    Starting the loop at 0 revisits earlier elements, so you generate repeats, and with a call like bt(i + 1) the new start is ignored and the recursion never terminates ([1] grows [1, 1, 1, …] until the stack overflows). The moving start index is what turns “choose any element” into “choose a later element”.

Where this shows up

  • Same skeleton, different pruning

    Combination sum, permutations, N-Queens and Sudoku all follow “choose, recurse, un-choose”. What changes is the loop’s range and a test that stops a branch early: a running sum over the target, a queen attacked, a digit already in the row.

  • SAT and constraint solvers

    The classic DPLL procedure behind SAT solvers is backtracking over variable assignments, with unit propagation as the pruning. Modern solvers add clause learning on top, but the search is still a decision tree like this one.

  • Test-case generation

    Exhaustive “every combination of n feature flags” tests is a power set: 10 flags is 1,024 runs, 20 flags is over a million. Knowing 2ⁿ is the budget is what makes teams switch to pairwise sampling.

  • Libraries

    Python’s itertools documentation gives a powerset recipe built from combinations, and itertools.combinations itself is the fixed-size slice of this tree.

SOLVE IT YOURSELF

Solve it: generate every subset

The power set, built by the choose-explore-undo loop that every backtracking problem shares. Write it in Python or TypeScript, running for real in your browser.

YOUR TASK

Implement subsets(nums): return every subset of the input, including the empty one and the full list — 2ⁿ of them in total.

HINTS — 5 IDEAS
  1. The shape is: record the current path, then for each remaining choice — choose, recurse, undo.
  2. Record the path at every node of the recursion, not just at the leaves. That is what makes this the power set rather than just the full-length combinations.
  3. Pass a start index and loop i from it, recursing with i + 1. That prevents reusing an element and prevents [1,2] and [2,1] both appearing.
  4. Append a copy of the path, not the path itself — otherwise every entry in your output aliases the same list and ends up empty.
  5. The undo (pop) is what lets one shared list serve the entire search.
CPython · WebAssembly

Questions

Subsets vs permutations — same code?

Same push-recurse-pop skeleton, different branching. Subsets decide include-or-skip from a moving start index (order-free, 2ⁿ). Permutations place each unused element into the next position (order matters, n!). Swap the loop and you switch problems.

Could I just use bitmasks instead?

For plain subsets, yes: iterate a counter from 0 to 2ⁿ−1 and read its bits as include flags. Backtracking earns its keep when you need to prune — skip whole branches that violate a constraint — which a flat bitmask loop cannot do.

Why is it O(n · 2ⁿ), not O(2ⁿ)?

There are 2ⁿ subsets, but copying each one into the results costs up to n (a subset can hold all n elements). Multiply and you get O(n · 2ⁿ) work overall.

One rhythm, a whole family of problems.

Push a choice, recurse, pop it back. Change the branch rule and add pruning — subsets become permutations, N-Queens, Sudoku.

Finished this one? 0 / 99 Algorithms done
NextCut the Dead Branches: Combination Sum Next on the “Try, fail, undo” ladder · rung 2 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms