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.
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.
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
- Call
backtrack(start=0, path=[]). - If
len(path) == k, record a copy and return. - Loop
ifromstartwhilen − i ≥ k − len(path)(enough elements remain): pusha[i], recurse withi + 1, pop. - For combination sum with reuse: base case
remaining == 0; prune whena[i] > remainingafter sorting; recurse withi(noti + 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 sizek". - 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.
1go(start, current):2 if len(current) == k: record(current); return3 for x in start .. n:4 if n - x + 1 < k - len(current): break // prune: not enough left5 current.push(x); go(x + 1, current)6 current.pop() // backtrackPseudocode
1backtrack(start, path):2 if len(path) == k: record(copy of path); return3 for i in start..n-1:4 if n - i < k - len(path): break # not enough left5 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 chosen8 if len(path) == k:9 out.append(path[:])10 return112 · Prune the loop bound12 need = k - len(path)13 for i in range(start, n - need + 2): # leave enough elements143 · Choose / explore / un-choose15 path.append(i)16 backtrack(i + 1)17 path.pop()18 19 backtrack(1)20 return out21 22 234 · Combination sum with unlimited reuse24def 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 return33 for i in range(start, len(cands)):34 if cands[i] > remaining:35 break # sorted: nothing later fits36 path.append(cands[i])37 backtrack(i, remaining - cands[i]) # i, not i + 1: reuse allowed38 path.pop()39 40 backtrack(0, target)41 return outrange(start, n - need + 2)is the prune: the upper bound is exclusive, hence+ 2instead of the+ 1used in the other languages.out.append(path[:])stores a copy once k elements are chosen.backtrack(i + 1)incombinationsforbids reuse;backtrack(i, ...)incombination_sumallows it.breakoncands[i] > remainingis valid only becausecandsis sorted.
itertools.combinations(range(1, n + 1), k)produces the same output lazily in C;itertools.combinations_with_replacementcovers multisets.rangeupper bounds are exclusive, which is where the+ 2comes from.- Depth is at most k (or target / min candidate), far below the recursion limit.
- Off-by-one in the
rangebound after translating<= n - need + 1from another language. - Appending
pathinstead ofpath[:]. - Using
continueinstead ofbreakin the sorted prune, which is correct but wastes the pruning benefit.
- Python's
rangehas an exclusive upper bound, so the prune readsn - need + 2versusi <= n - need + 1in C++/JS/TS. - Only Python has a built-in combinations generator (
itertools); C++ can emulate withprev_permutationover a selector mask; JS/TS hand-roll it. - JS/TS require
sort((a, b) => a - b)before the sorted-prunebreakis valid.
Complexity
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
- 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.
- Only the count
C(n, k)is needed — compute it with Combinatorics (Pascal or multiplicative formula). - Counting the number of ways to reach a sum — Coin Change / Unbounded Knapsack DP does it in
O(n · target). - Selections must be ordered — that is Permutations.
Alternatives
Common mistakes
- Off-by-one in the prune bound
i <= n - need + 1(1-indexed) — test withk == n. - In combination sum, recursing with
i + 1when reuse is allowed (misses[2,2,3]) or withiwhen it is not (produces repeats). - Forgetting to sort before
break-ing onc[i] > remaining; with unsorted input usecontinueinstead. - 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.
- Recursion versus iterationIntermediate
- Recognizing a dynamic-programming problemAdvanced
- Word SearchAdvanced
Example problems
Check yourself
Answer out loud or on paper first, then compare. These come from the interview questions linked to this lesson.
When is recursion the right tool, when is iteration better, and what does recursion cost?
Show a strong answerHide the 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 a10^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 →How do you recognize that a problem needs dynamic programming, and how do you go from recognition to a working solution?
Show a strong answerHide the 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, orn ≤ 20for 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
Full interview question, with follow-ups and red flags →n = 10^5and the state would beO(n^2), they look for a monotonic-queue or segment-tree optimization or a different formulation.Convert inorder traversal to iteration.
Show a strong answerHide the 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 →