BacktrackingAlgorithmaka k-subsets, n choose k, combination sum

Combinations (n choose k)

Enumerate all size-k subsets of n elements using the start-index template with a size-based base case and a "not enough elements left" prune.

▶ VisualizePattern: BacktrackingPractice (2)
Progress
Before this, know:ArrayStack

You have not marked these as done yet. Read on anyway if they feel familiar; come back to them if something here does not land.

Overview

A combination is an unordered selection of exactly k items from n; there are C(n, k) = n! / (k!(n−k)!) of them. The algorithm is the Subsets (Power Set) start-index template with two changes: record only when len(path) == k, and prune when the remaining elements cannot fill the path (n − i < k − len(path)).

Combination Sum generalizes the base case from "size equals k" to "sum equals target" and, when reuse is allowed, recurses with i instead of i + 1.

backtrackingC(n,k)start indexpruningcombination sum

Intuition

A mental model before the formal terms.

Choosing 3 people from a line of 7: point at someone, then only consider people to their right for the next pick. That rule alone stops you from picking the same trio in a different order.

The prune is counting how many people remain to your right: if you still need 2 more picks and only 1 person is left, stop looking down this branch.

How it works

  1. Call backtrack(start=0, path=[]).
  2. If len(path) == k, record a copy and return.
  3. Loop i from start while n − i ≥ k − len(path) (enough elements remain): push a[i], recurse with i + 1, pop.
  4. For combination sum with reuse: base case remaining == 0; prune when a[i] > remaining after sorting; recurse with i (not i + 1).

Why it works

Each k-combination corresponds to exactly one increasing index sequence of length k, which the start-index loop enumerates once.

The remaining-count prune is exact: once fewer than k − len(path) elements remain, no completion exists, so skipping is safe and cuts the tree from O(2^n) nodes to roughly O(C(n,k) · k).

Recognition

How to tell a problem wants this.

  • "Choose exactly k", "all combinations that sum to target", "select a group of size k".
  • Order of chosen items is explicitly irrelevant — output [1,2] but not [2,1].
  • Small n (≤ 20) and an output list of combinations is expected.

Interactive visualization

Play, step, change the input. ← → and space work too.

Call stack (top first)
empty
Combinations (0)
empty
1/27Choose 2 of {1..4}: pick numbers in increasing order so each combination is generated exactly once.
Call on the stackCall returnedJust placed
1go(start, current):
2 if len(current) == k: record(current); return
3 for x in start .. n:
4 if n - x + 1 < k - len(current): break // prune: not enough left
5 current.push(x); go(x + 1, current)
6 current.pop() // backtrack
Variables
n4
k2
Complexity
worst O(k · C(n, k))
space O(k)
Speed

Pseudocode

1backtrack(start, path):
2 if len(path) == k: record(copy of path); return
3 for i in start..n-1:
4 if n - i < k - len(path): break # not enough left
5 path.push(a[i])
6 backtrack(i + 1, path)
7 path.pop()
8backtrack(0, [])

Implementations

1def combinations(n: int, k: int) -> list[list[int]]:
2 """All k-combinations of 1..n."""
3 out: list[list[int]] = []
4 path: list[int] = []
5
6 def backtrack(start: int) -> None:
71 · Base case: k chosen
8 if len(path) == k:
9 out.append(path[:])
10 return
112 · Prune the loop bound
12 need = k - len(path)
13 for i in range(start, n - need + 2): # leave enough elements
143 · Choose / explore / un-choose
15 path.append(i)
16 backtrack(i + 1)
17 path.pop()
18
19 backtrack(1)
20 return out
21
22
234 · Combination sum with unlimited reuse
24def combination_sum(cands: list[int], target: int) -> list[list[int]]:
25 cands = sorted(cands)
26 out: list[list[int]] = []
27 path: list[int] = []
28
29 def backtrack(start: int, remaining: int) -> None:
30 if remaining == 0:
31 out.append(path[:])
32 return
33 for i in range(start, len(cands)):
34 if cands[i] > remaining:
35 break # sorted: nothing later fits
36 path.append(cands[i])
37 backtrack(i, remaining - cands[i]) # i, not i + 1: reuse allowed
38 path.pop()
39
40 backtrack(0, target)
41 return out
Walkthrough
  1. range(start, n - need + 2) is the prune: the upper bound is exclusive, hence + 2 instead of the + 1 used in the other languages.
  2. out.append(path[:]) stores a copy once k elements are chosen.
  3. backtrack(i + 1) in combinations forbids reuse; backtrack(i, ...) in combination_sum allows it.
  4. break on cands[i] > remaining is valid only because cands is sorted.
Complexity (this implementation)
time O(k * C(n, k)) for combinations; exponential for combination_sum · space O(k) recursion depth plus output
Language notes
  • itertools.combinations(range(1, n + 1), k) produces the same output lazily in C; itertools.combinations_with_replacement covers multisets.
  • range upper bounds are exclusive, which is where the + 2 comes from.
  • Depth is at most k (or target / min candidate), far below the recursion limit.
Common mistakes in this language
  • Off-by-one in the range bound after translating <= n - need + 1 from another language.
  • Appending path instead of path[:].
  • Using continue instead of break in the sorted prune, which is correct but wastes the pruning benefit.
Language differences that matter here
  • Python's range has an exclusive upper bound, so the prune reads n - need + 2 versus i <= n - need + 1 in C++/JS/TS.
  • Only Python has a built-in combinations generator (itertools); C++ can emulate with prev_permutation over a selector mask; JS/TS hand-roll it.
  • JS/TS require sort((a, b) => a - b) before the sorted-prune break is valid.

Complexity

Best
—
Average
—
Worst
O(k · C(n, k))
Space
O(k)

With the remaining-count prune every internal node leads to at least one leaf, so work is proportional to output size. Combination sum is exponential in target / min(candidate).

Compare growth rates in the Complexity Explorer →

When to use — and when not to

Use it when
  • Enumerate all fixed-size selections, or all multisets summing to a target, for small inputs.
  • Search over selections where a cheap prefix test (sum, size, remaining budget) prunes most branches.
Avoid it when

Alternatives

Common mistakes

  • Off-by-one in the prune bound i <= n - need + 1 (1-indexed) — test with k == n.
  • In combination sum, recursing with i + 1 when reuse is allowed (misses [2,2,3]) or with i when it is not (produces repeats).
  • Forgetting to sort before break-ing on c[i] > remaining; with unsorted input use continue instead.
  • Combination Sum II (each element once, duplicates in input) needs the Subsets (Power Set) duplicate skip i > start && c[i] == c[i-1].

Interview patterns

  • Combination Sum I / II / III: vary reuse, duplicate handling, and size constraint.
  • Factor combinations, palindrome partitioning: the "element" is a chunk of the input, chosen from a start index.
  • Phone-keypad letter combinations: cross product of per-position choice sets, no start index needed.
Interview questions on this
Mock interviews

Example problems

Check yourself

Answer out loud or on paper first, then compare. These come from the interview questions linked to this lesson.

  1. When is recursion the right tool, when is iteration better, and what does recursion cost?

    Show a strong answer

    Recursion is the right tool when the problem is defined in terms of smaller copies of itself and there is state to remember on the way back up: tree traversals, Divide and Conquer, backtracking over choices, and DFS where you undo a choice after exploring it. In those cases the call stack is doing real work — holding the path — and an iterative version would need an explicit stack that mirrors it exactly.

    Iteration is better when the recursion is linear (one recursive call, nothing done after it — tail-recursive), because then the stack holds nothing useful and the depth is pure cost. A linked list walk, a linear DP, and a binary search should be loops. The cost of recursion is O(depth) stack memory and a real risk of stack overflow: Python defaults to about 1000 frames, and a DFS over a 10^5-node path graph will crash.

    A strong candidate knows the conversion: replace the call stack with an explicit Stack holding the same frame data, and turn top-down Memoization (Top-Down DP) into bottom-up Tabulation (Bottom-Up DP) when depth is the problem. They also note that iterative code is easier to instrument and debug but recursive code is often shorter and closer to the proof of correctness.

    Full interview question, with follow-ups and red flags →
  2. How do you recognize that a problem needs dynamic programming, and how do you go from recognition to a working solution?

    Show a strong answer

    The surface signals: "number of ways", "minimum cost", "maximum value", "is it possible", over a sequence of choices where each choice constrains later ones; constraints small enough for a polynomial state space (n ≤ 5000, or n ≤ 20 for bitmask); and a brute-force recursion that would revisit the same situation many times. But a strong candidate verifies two properties rather than trusting the phrasing. Optimal substructure: the optimal answer for the whole is built from optimal answers to subproblems — if the best answer for a prefix might require a *suboptimal* answer for a shorter prefix, DP does not apply. Overlapping subproblems: the recursion tree contains the same subproblem repeatedly; if not, plain recursion or divide and conquer is already efficient.

    From recognition to solution is a fixed procedure. 1. Write the brute-force recursion — what decision is made at each step, what information the rest of the problem needs. 2. Name the state: the minimal set of parameters that determine the answer to the remainder. This is the hard step; "index i" is the state for House Robber, "index and remaining capacity" for 0/1 Knapsack, "pair of indices" for Longest Common Subsequence, "index and previous element" for Longest Increasing Subsequence. If the state grows unboundedly, DP is wrong or the state is wrong. 3. Write the transition from the choices. 4. Identify base cases and order — memoize top-down, or tabulate in an order where dependencies are already computed. 5. Complexity: number of states × work per transition. 6. Reconstruct the choice if the problem wants the solution, not just the value.

    They also know what DP is structurally: shortest path on the DAG of states. That view explains why cyclic dependencies mean the state is wrong, why the topological order of tabulation matters, and why a problem with a greedy choice property can skip DP entirely. And they check for the failure mode of "DP for everything": if n = 10^5 and the state would be O(n^2), they look for a monotonic-queue or segment-tree optimization or a different formulation.

    Full interview question, with follow-ups and red flags →
  3. Convert inorder traversal to iteration.

    Show a strong answer

    Explicit stack: push the current node and go left until null, then pop, visit, and move to the right child. The stack holds exactly the ancestors whose left subtree is done.

    Full interview question, with follow-ups and red flags →