Combinations
medium 20 minCombination problems pick items where order does not matter.
See it run
Choose k of n with a start index, hit a target sum with or without reuse, skip duplicate values, and spell every phone-keypad word, one decision tree at a time.
Operations
Choose 2 of 4
List every 2-number combination of 1..4. A start index means each call only looks at bigger numbers, so [2,1] is never built as a copy of [1,2]; the loop bound stops a branch that could never reach k numbers.
Step 1 of 8
Start: need 2 numbers
path [ ] · need 2
backtrack(1) starts with an empty path, so it still needs 2 numbers. The loop runs i from 1 to n - need + 1 = 3: starting with 4 would leave nothing bigger to pick second, so 4 is never tried at this level.
Step 1: Start: need 2 numbers
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): # prune: leave room for the rest path.append(i) # choose backtrack(i + 1) # explore: only bigger numbers path.pop() # unchoose backtrack(1) return result- Time
- O(k · C(n, k))
- Space
- O(k) path and stack
- answers
- C(4, 2) = 6
- calls with the bound
- 10
- calls without it
- 11
Stop at depth k, start the loop at i + 1, and end it where there are still enough numbers left: that is the whole combinations template.
In the real world
The same combinations doing real jobs. Pick one and step through it.
A shop sells two items, one costing 1 and one costing 2. You may buy any number of each and want every way to spend exactly 4. A basket is a combination: buying 1 then 2 is the same basket as 2 then 1.
Step 1 of 5
An empty basket
spent 0 / 4
Prices sorted: [1, 2]. Budget 4, nothing spent. Reuse is allowed, so each call may pick the same item again.
Step 1: An empty basket
print(combination_sum([1, 2], 4)) # [[1, 1, 1, 1], [1, 1, 2], [2, 2]]Common mistakes
The bugs interviewers watch for, with the fix beside each.
Recursing with i + 1 when reuse is allowed (or i when it is not)
criticalIn Combination Sum a candidate may repeat, so the call must pass
i. Passingi + 1silently loses[2,2,3]. In Combination Sum II it is the other way round: passingireuses an item and invents answers.Wrongpath.append(candidates[i])backtrack(i + 1, total + candidates[i]) # Combination Sum: [2, 2, 3] is never builtRightpath.append(candidates[i])backtrack(i, total + candidates[i]) # reuse allowed: stay on iSkipping duplicates with i > 0 instead of i > start
criticali > 0also skips the second copy one level deeper, where it is a legitimate pick. On [1, 2, 2] with target 5 that loses [1, 2, 2]. Only repeats at the same level are duplicates.Wrongif i > 0 and candidates[i] == candidates[i - 1]: continue # also blocks [1, 2, 2]Rightif i > start and candidates[i] == candidates[i - 1]: continue # only the same levelBreaking on overshoot without sorting
majorbreakassumes every later candidate is at least as big. On unsorted [2, 6, 3, 7] with target 7, the call for [2, 2] meets 6 before 3, breaks, and never finds [2, 2, 3].Wrongdef combination_sum(candidates, target): # no sort ... if total + candidates[i] > target: breakRightdef combination_sum(candidates, target): candidates.sort() # now break is safe ... if total + candidates[i] > target: breakStarting the loop at 0 every time
majorWithout a start index each combination is built in every order: [2,2,3], [2,3,2] and [3,2,2] are all saved. Order does not matter in a combination, so only look forward.
Wrongfor i in range(len(candidates)): # looks backwards too path.append(candidates[i]) backtrack(i, total + candidates[i]) path.pop()Rightfor i in range(start, len(candidates)): # only this index and later path.append(candidates[i]) backtrack(i, total + candidates[i]) path.pop()Off-by-one in the k-of-n bound
minorThe last useful start is n - need + 1, so Python's range must end at n - need + 2. Ending at n - need + 1 drops the last option: combine(4, 2) loses [3, 4].
Wrongfor i in range(start, n - need + 1): # misses i = n - need + 1Rightfor i in range(start, n - need + 2): # i can still be n - need + 1Returning [""] for an empty phone number
minorWith no digits the base case fires at once and saves the empty string. The expected answer for no digits is no combinations at all.
Wrongdef letter_combinations(digits): result, path = [], [] ... # "" gives [""]Rightdef letter_combinations(digits): if not digits: return [] ...
Interview tips
How to explain it
- A combination is a set, so build it in index order with a start index; that alone stops reordered duplicates.
- Stop at depth k for k of n, or at total == target for a sum.
- Reuse means recurse with i, use once means i + 1.
- The output can have C(n, k) answers, so no method beats O(k · C(n, k)) when you must list them.
During the interview
- Ask: can an element repeat? Can the input contain duplicates? Are all numbers positive?
- Sort first, then name your two prunes: break on overshoot, skip equal neighbours at the same level.
- Draw the tree for a tiny input, such as 2 of 4, before coding.
Memory tricks
- SPEC: Sort, Prune, Explore, Check.
- i keeps it, i + 1 moves on.
- Same value, same level, skip it.
Watch out
- Break is only safe on sorted input with no negative numbers.
- Save path[:], not path.
- Counting only? Use C(n, k) or DP, not a full enumeration.