Combination Sum solution explained
Combination Sum is solved by backtracking over the sorted candidates with a start index: add a candidate, recurse with the same index because a value may be reused, subtract it from the remaining target, and stop a branch as soon as the next candidate is larger than what remains. Recording a combination only when the remainder hits exactly zero gives every answer once, with no duplicates in a different order.
By Evin JohnPublished 7 min read
The problem in our words
You are given a list of distinct positive integers, the candidates, and a positive target. Find every combination of candidates whose sum equals the target. Each candidate may be used any number of times. Two combinations count as the same if they contain the same values with the same multiplicities, whatever the order. Return them in any order.
| Candidates | Target | Combinations |
|---|---|---|
| [3, 4, 5] | 11 | [3, 3, 5], [3, 4, 4] |
| [6, 4] | 12 | [4, 4, 4], [6, 6] |
| [2, 7] | 9 | [2, 7] |
| [5] | 3 | None, so the answer is an empty list |
| [3, 4, 5] | 20 | Six combinations, from [4, 4, 4, 4, 4] to [3, 3, 3, 3, 3, 5] |
Check the assumptions aloud: are the candidates distinct and strictly positive? Both matter. A zero would allow endless combinations, and negative values would remove the ability to stop a branch once the sum passes the target. If repeated candidates are possible, the deduplication rule changes too.
What interviewers look for
This is a step up from plain subsets because of the reuse rule. The interviewer wants to see that you know exactly where the index changes: recursing with i allows reuse, recursing with i + 1 forbids it, and never going below the start index prevents [4, 3, 4] from appearing beside [3, 4, 4]. They also listen for pruning, since the sorted early break is what keeps the search practical.
Related twists
- Each candidate may be used at most once, and the list may contain repeats. Recurse with i + 1, sort, and skip a value equal to its left neighbour within the same loop.
- Exactly k numbers from 1 to 9, each used once. Add a length check and a fixed candidate range.
- Only the number of combinations is needed. Do not list them; count with a one-dimensional DP, shown below.
- Order matters, so [3, 4, 4] and [4, 3, 4] are different. Swap the loops of the DP, or drop the start index in the search. The counts grow quickly.
Backtracking with pruning
Sort the candidates. A recursive helper receives a start index and the remaining amount. If the remainder is zero, copy the current combination into the answer. Otherwise loop over candidates from the start index. If a candidate is larger than the remainder, stop the loop, since every later candidate is larger still. Otherwise add it, recurse with the same index and a smaller remainder, then remove it.
def combination_sum(candidates, target):
nums = sorted(candidates)
result, chosen = [], []
def build(start, remaining):
if remaining == 0:
result.append(chosen[:])
return
for i in range(start, len(nums)):
if nums[i] > remaining:
break # sorted, so every later value is too big as well
chosen.append(nums[i])
build(i, remaining - nums[i]) # i, not i + 1: reuse is allowed
chosen.pop()
build(0, target)
return resultRun it on [3, 4, 5] with target 11. The search goes 3, 3, 3 (remainder 2, and 3 is too big, so the branch ends), then 3, 3, 4 (remainder 1, another dead end), then 3, 3, 5 (remainder 0, recorded), then 3, 4, 4 (recorded), then 3, 4 with 5 too big, and so on. Every recorded list is in non-decreasing order, which is a quick way to see there are no duplicates.
Take or skip, in JavaScript
A second way to frame the same search is a binary choice at each candidate: take it again and stay on it, or leave it behind for good and move to the next one. This version does not sort, so it cannot break early; instead it stops when the remainder goes negative. It is often easier to prove correct, because each combination corresponds to exactly one path of take and skip decisions.
function combinationSum(candidates, target) {
const out = [];
const pick = [];
function decide(i, left) {
if (left === 0) {
out.push(pick.slice());
return;
}
if (i === candidates.length || left < 0) return;
pick.push(candidates[i]); // take candidates[i], and stay on it
decide(i, left - candidates[i]);
pick.pop();
decide(i + 1, left); // or leave it behind for good
}
decide(0, target);
return out;
}Counting instead of listing
If only the number of combinations is asked, listing them wastes time. This is the same count as the number of ways to make an amount from coin values. Fill an array where ways[t] holds the number of multisets that sum to t. Looping over candidates on the outside and totals on the inside counts each multiset once, in O(len(candidates) × target) time.
def count_combinations(candidates, target):
ways = [1] + [0] * target # ways[t]: multisets that add up to t
for c in candidates: # outer loop over values counts each multiset once
for total in range(c, target + 1):
ways[total] += ways[total - c]
return ways[target]How expensive is it
The output can grow very quickly with the target, so the honest answer is that the running time depends on the output size and the shape of the search tree. A common bound: with c candidates, a smallest candidate m and target T, the tree has depth at most T / m and branching at most c, which gives O(c^(T/m)) nodes in the worst case, each costing up to T / m to copy a result. Pruning keeps real runs far smaller. Extra space besides the output is the recursion depth, O(T / m).
| Approach | Time | Extra space | Returns |
|---|---|---|---|
| Sorted backtracking with early break | Output-sensitive, O(c^(T/m)) bound | O(T / m) | All combinations |
| Take or skip recursion | Same bound, fewer early exits | O(c + T / m) | All combinations |
| DP over totals | O(c × T) | O(T) | The count only |
Edge cases
- No combination possible, such as [5] with target 3: return an empty list.
- A target equal to one candidate: that candidate alone is one answer.
- A target reachable only through heavy reuse of the smallest value.
- Candidates given out of order: sort before relying on the early break.
- A large target with small candidates, where the output itself explodes. Say so rather than promise speed.
Typical errors
- Recursing with i + 1 and losing the reuse that the problem allows.
- Looping from 0 in every call, producing [3, 4, 4], [4, 3, 4] and [4, 4, 3].
- Using continue instead of break after sorting, which is correct but throws away the pruning.
- Appending the shared list rather than a copy.
- Swapping the DP loops for the counting version and returning ordered counts.
Explaining the reuse rule
Fictional example
- Candidate
- I'll sort the candidates and backtrack with a start index and a remaining amount.
- Candidate
- When I add a candidate I recurse with the same index, because it can be used again. I never go to an earlier index, so each combination comes out in non-decreasing order and only once.
- Candidate
- Since the list is sorted, once a candidate is bigger than what remains I can break, not just skip.
- Interviewer
- And if I only wanted how many combinations there are?
- Candidate
- Then a one-dimensional DP over totals, candidates in the outer loop so each multiset counts once. That's candidates times target.
Related problems
Subsets is the same start-index template with no target and no reuse. Permutations changes the rule to use each element exactly once in every order. On the heap side, Last Stone Weight and Find Median from Data Stream are good contrasts if you are mixing topics in one session.
Practicing it with Natively
Natively can capture a problem like this from your screen on Mac or Windows and set out the backtracking idea, the pruning step and code you can run yourself. That makes it a quick check when your output has unexpected duplicates. If you practice explaining the reuse rule to a friend on a call, Natively keeps a transcript you can reread later. See how AI helps with coding interviews.
Questions people ask
How do you solve Combination Sum?
Sort the candidates and backtrack with a start index and the remaining target. Recurse with the same index to allow reuse, record a combination when the remainder is zero, and break once a candidate exceeds the remainder.
How does Combination Sum avoid duplicate combinations?
It never chooses a candidate earlier than the current start index, so every combination is built in non-decreasing order. Each multiset then has exactly one way to be built.
What is the time complexity of Combination Sum?
It depends on the output. A common worst-case bound is O(c^(T/m)) for c candidates, target T and smallest candidate m, with recursion depth O(T / m). Sorting and pruning keep real runs much smaller.
What is the difference between Combination Sum and Combination Sum II?
In the second version each candidate may be used at most once and the input may contain repeats. Recurse with i + 1 and skip equal neighbours within the same loop.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
