AlgoViz

Combinations

medium 20 min

Combination problems pick items where order does not matter.

Video lesson · Chapter 1 of 9

Balance the sample crate

0:00 / 7:07

Combinations in 75 seconds

1:26Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Look forward only. Each call picks from a start index onwards, so a set is built in one order and never repeated

Understand it

Start here

Recap: backtracking with a start index

  • You already know the rhythm

    Choose, explore, unchoose, from Backtracking. This page only changes which options each call may choose from and when it stops.

  • Subsets are the parent

    The start-index loop from Subsets saves every node. Combinations save only the nodes that meet a rule: length kk, or a total equal to the target.

  • Counting is a separate topic

    Why there are (nk)\binom{n}{k} ways to choose is covered in Combinations vs permutations. Here we list them in code.

A combination is a selection where order does not matter: {2, 3} and {3, 2} are the same team, the same basket, the same answer. A permutation cares about order, which is why Permutations uses a used array instead of a start index.

The count

How many answers: C(n, k)

Choose k of n

(nk)=n!k! (n−k)!,(42)=242⋅2=6,(93)=84\binom{n}{k} = \frac{n!}{k!\,(n-k)!}, \qquad \binom{4}{2} = \frac{24}{2 \cdot 2} = 6, \qquad \binom{9}{3} = 84
The number of answers a k-of-n search must output. Choosing 2 of 4 gives exactly the six pairs the visualizer builds.

The output-size bound

T(n,k)=Θ ⁣(k⋅(nk)),(nk)≤(n⌊n/2⌋)≈2nπn/2,∑k=0n(nk)=2nT(n, k) = \Theta\!\left(k \cdot \binom{n}{k}\right), \qquad \binom{n}{k} \le \binom{n}{\lfloor n/2 \rfloor} \approx \frac{2^{n}}{\sqrt{\pi n / 2}}, \qquad \sum_{k=0}^{n} \binom{n}{k} = 2^{n}
Each answer has kk numbers to copy, so listing them costs at least k⋅(nk)k \cdot \binom{n}{k}; with the pruning bound the search does not cost more than a constant factor above that. The worst size is k=n/2k = n/2, and all sizes together are the 2n2^n subsets.
nk(nk)\binom{n}{k}Feels like
426instant
105252instant
2010184,756fine
3015155,117,520too many to list
Symmetry helps: (nk)=(nn−k)\binom{n}{k} = \binom{n}{n-k}, so choosing 18 of 20 is as cheap as choosing 2 of 20.

Pattern 1

Choose k of n

Build the combination in increasing order. Each call has a start value and may only pick numbers from there upwards, so [2, 1] is never built as a copy of [1, 2]. When the path holds kk numbers, save a copy and return: answers live only at depth kk.

One call of backtrack(start)

The loop never starts below start and never goes past the last value that still leaves room for the rest of the combination.
Python
def combine(n, k):    result, path = [], []    def backtrack(start):        if len(path) == k:            result.append(path[:])          # depth k: one combination            return        need = k - len(path)        for i in range(start, n - need + 2):   # leave room for the rest            path.append(i)                  # choose            backtrack(i + 1)                # explore: only bigger numbers            path.pop()                      # unchoose    backtrack(1)    return resultprint(combine(4, 2))   # [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]print(len(combine(10, 5)))   # 252
combine(4, 2) gives the six pairs from the visualizer, in the order the tree is walked.
Edit and run it in your browser

Pruning

Stop when not enough items remain

The last useful start

i+(need−1)≤n  ⟺  i≤n−need+1,need=k−∣path∣i + (\text{need} - 1) \le n \;\Longleftrightarrow\; i \le n - \text{need} + 1, \qquad \text{need} = k - |\text{path}|
If you pick ii now, the remaining need−1\text{need} - 1 picks must all be bigger than ii and at most nn. Python's range excludes its end, so the loop is range(start, n - need + 2).

combine(4, 2) with the bound

Six green leaves at depth 2 are the answers. [4] would need one more number bigger than 4, so the bound removes it before the call is made.

Pattern 2

Combination Sum: reuse allowed

Given distinct positive candidates and a target, list every combination that adds up to the target, using any candidate as often as you like. Two changes from k of n: the base case is total == target, and the call passes i instead of i + 1, so the same candidate stays available. Sort first, and when total + candidates[i] > target you can break: every later candidate is at least as big.

combination_sum([2, 3, 6, 7], 7)

Step by step: try 2 (sum 2), 2 again (4), 2 again (6) and the next 2 overshoots; back up, 3 makes exactly 7; back up, 6 makes 10, so break and never look at 7. The answers are [2,2,3] and [7].
Python
def combination_sum(candidates, target):    candidates = sorted(candidates)         # sorted: one overshoot ends the loop    result, path = [], []    def backtrack(start, total):        if total == target:            result.append(path[:])            return        for i in range(start, len(candidates)):            if total + candidates[i] > target:                break                       # every later candidate is bigger            path.append(candidates[i])            backtrack(i, total + candidates[i])   # i, not i + 1: reuse allowed            path.pop()    backtrack(0, 0)    return resultprint(combination_sum([2, 3, 6, 7], 7))   # [[2, 2, 3], [7]]print(combination_sum([2, 3, 5], 8))      # [[2, 2, 2, 2], [2, 3, 3], [3, 5]]print(combination_sum([1, 2], 4))         # [[1, 1, 1, 1], [1, 1, 2], [2, 2]]
Three examples, run with reuse allowed.
Edit and run it in your browser

How deep can it go?

depth≤⌊Tm⌋,nodes=O ⁣(n T/m),space=O ⁣(Tm)\text{depth} \le \left\lfloor \frac{T}{m} \right\rfloor, \qquad \text{nodes} = O\!\left(n^{\,T/m}\right), \qquad \text{space} = O\!\left(\frac{T}{m}\right)
TT is the target and mm the smallest candidate: the longest combination is mm repeated. For [2,3,6,7][2, 3, 6, 7] and 77 that is ⌊7/2⌋=3\lfloor 7/2 \rfloor = 3 levels.

One character

i or i + 1

backtrack(i, ...): reuse allowed

  • Combination Sum: the same candidate may appear many times, e.g. [2, 2, 2].
  • Depth is bounded by the target, not by n.
  • [2, 3, 5] to 8 gives [2,2,2,2], [2,3,3] and [3,5].

backtrack(i + 1, ...): each once

  • Combination Sum II and III, k of n: every item is used at most once.
  • Depth is at most n, so the tree is at most the 2ⁿ subsets.
  • [2, 3, 5] to 8 gives only [3,5].
ProblemRecurse withStop whenExtra prune
Combinations, k of ni + 1len(path) == ki <= n - need + 1
Combination Sumitotal == targetsorted, break on overshoot
Combination Sum IIi + 1total == targetskip equal neighbour at the same level
Combination Sum IIIi + 1 (digits 1 to 9)len(path) == kbreak when the digit exceeds what remains
Phone lettersindex + 1index == len(digits)none: every leaf is an answer
Every row is the same start-index loop. Only the recursive argument, the base case and the prune change.

Pattern 3

Combination Sum II: duplicates in the input

Now each item may be used once, but the input can repeat values, as in [10, 1, 2, 7, 6, 1, 5]. Picking the first 1 or the second 1 builds the same combinations, so the output would contain duplicates. Sort to put equal values side by side, then in the loop skip a value equal to the one before it at the same level.

The loop body in Combination Sum II

On [1, 2, 2, 3] with target 5 the skip fires twice: once for the second 2 under [1] and once at the root. The answers are [1,2,2] and [2,3], each once.
Python
def combination_sum2(candidates, target):    candidates = sorted(candidates)         # equal values side by side    result, path = [], []    def backtrack(start, total):        if total == target:            result.append(path[:])            return        for i in range(start, len(candidates)):            if i > start and candidates[i] == candidates[i - 1]:                continue                    # same value already tried at this level            if total + candidates[i] > target:                break            path.append(candidates[i])            backtrack(i + 1, total + candidates[i])   # each item once            path.pop()    backtrack(0, 0)    return resultprint(combination_sum2([10, 1, 2, 7, 6, 1, 5], 8))   # [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]print(combination_sum2([2, 1, 3, 2], 5))             # [[1, 2, 2], [2, 3]]
The classic input. The second 2 inside [1, 2] is allowed because there it is the first option at its level.
Edit and run it in your browser

Pattern 4

Combination Sum III: k digits from 1 to 9

Find every set of kk different digits from 1 to 9 that adds up to nn. It is k of n and Combination Sum at once: the candidates are the digits 1 to 9, each used once (d + 1), and the base case checks both the length and the total. The digits are already sorted, so a digit bigger than what remains breaks the loop.

Reject impossible targets before searching

1+2+⋯+k⏟smallest=k(k+1)2  ≤  n  ≤  9+8+⋯+(10−k)⏟largest=k(19−k)2\underbrace{1 + 2 + \cdots + k}_{\text{smallest}} = \frac{k(k+1)}{2} \;\le\; n \;\le\; \underbrace{9 + 8 + \cdots + (10-k)}_{\text{largest}} = \frac{k(19-k)}{2}
For k=3k = 3 the target must lie between 6 and 24. Outside that range the answer is empty without a single call. At most (9k)≤(94)=126\binom{9}{k} \le \binom{9}{4} = 126 sets are ever possible.
Python
def combination_sum3(k, n):    if not (k * (k + 1) // 2 <= n <= k * (19 - k) // 2):        return []                           # impossible target    result, path = [], []    def backtrack(start, remaining):        if len(path) == k:            if remaining == 0:                result.append(path[:])            return        for d in range(start, 10):            if d > remaining:                break                       # digits only get bigger            path.append(d)            backtrack(d + 1, remaining - d) # each digit once            path.pop()    backtrack(1, n)    return resultprint(combination_sum3(3, 7))    # [[1, 2, 4]]print(combination_sum3(3, 9))    # [[1, 2, 6], [1, 3, 5], [2, 3, 4]]print(combination_sum3(4, 30))   # [[6, 7, 8, 9]]: 9 + 8 + 7 + 6 is the largest sumprint(combination_sum3(4, 31))   # []: rejected before any call
Three digits that add up to 9, and the range check that rejects 31 for four digits at once.
Edit and run it in your browser

Pattern 5

Letter combinations of a phone number

Each keypad digit maps to 3 or 4 letters; list every string made by picking one letter per digit. This is the one combination pattern with no start index: each level draws from a different digit's letters, so the index into the digit string is the depth, and nothing can repeat.

"23": one level per digit

Three letters, then three letters: nine leaves, and every leaf is an answer.

A product of choices

∣result∣=∏j=1n∣letters(dj)∣≤4n,T=O(n⋅4n),for 23: 3×3=9|\text{result}| = \prod_{j=1}^{n} |\text{letters}(d_j)| \le 4^{n}, \qquad T = O(n \cdot 4^{n}), \qquad \text{for 23: } 3 \times 3 = 9
Digits 7 and 9 have four letters, the rest three, so nn digits give at most 4n4^n strings of length nn.
Python
PHONE = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl",         "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}def letter_combinations(digits):    if not digits:        return []    result, path = [], []    def backtrack(index):        if index == len(digits):            result.append("".join(path))            return        for ch in PHONE[digits[index]]:            path.append(ch)            backtrack(index + 1)            path.pop()    backtrack(0)    return resultprint(letter_combinations("23"))        # ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']print(len(letter_combinations("79")))   # 16
An empty input returns an empty list, not a list holding the empty string.
Edit and run it in your browser

Complexity

What each variant costs

ProblemTimeSpace (path + stack)Why
k of nO(k⋅(nk))O(k \cdot \binom{n}{k})O(k)O(k)(nk)\binom{n}{k} answers, each copied in O(k)O(k)
Combination SumO(nT/m)O(n^{T/m}) worst caseO(T/m)O(T/m)Up to nn choices on each of T/mT/m levels
Combination Sum IIO(n⋅2n)O(n \cdot 2^n)O(n)O(n)Each item in or out once; sorting adds O(nlog⁡n)O(n \log n)
Combination Sum IIIO(k⋅(9k))O(k \cdot \binom{9}{k})O(k)O(k)At most 126 digit sets
Phone lettersO(n⋅4n)O(n \cdot 4^n)O(n)O(n)Up to 4 letters per digit
Space counts only the working path, not the output. The old version of this page called Combination Sum O(2n)O(2^n); with reuse the depth depends on the target, so O(nT/m)O(n^{T/m}) is the honest bound.

Choosing

Which template is it?

SPEC: a four-step mnemonic
  1. 1Sortcandidates ascending
  2. 2Prunesum + c[i] > target: break
  3. 3Explorerecurse with i or i + 1
  4. 4Checksum == target: save
Repeat: back to Sort

Sort once, then every call loops through prune, explore and check. The loop arrow is the for-loop moving to the next candidate.

Pick the variant from the problem statement

If the question asks how many, not which, stop: C(n, k) or a DP table answers it without listing anything.
  • The same skip elsewhere

    Subsets II and Permutations II use the identical line: sort, then skip a value equal to its left neighbour at the same level.

  • Combination Sum IV is DP

    It counts ordered sequences, so [1, 2] and [2, 1] are different. That is a counting problem: use dynamic programming from DP core, not backtracking.

  • itertools.combinations

    Python's library lists k of n in the same order as our template. Use it in real code; write the backtracking in interviews.

Recap

Key takeaways

Key points

  • A combination ignores order, so build it in index order with a start index; that alone removes reordered duplicates.
  • k of n stops at depth k and loops only up to n - need + 1, so every branch can still be completed.
  • There are C(n, k) answers, so listing them costs at least O(k · C(n, k)).
  • Combination Sum recurses with i (reuse); Combination Sum II and III recurse with i + 1 (each once).
  • Sort, then break on the first overshoot; that is only safe with sorted, non-negative numbers.
  • Duplicates: skip c[i] when i > start and c[i] == c[i - 1]. Same value across one level is a duplicate; down the tree it is fine.
  • Phone letters have no start index: the digit index is the depth and every leaf is an answer.
  • Save path[:], and when only a count is asked, reach for the formula or DP instead.

Sources