Combination Sum II solution explained
Combination Sum II asks for every distinct group of numbers from a list that adds up to a target, where each position in the list can be used once but the list itself may contain repeated values. Sort the list, then backtrack: at each depth try each value at most once (skip a candidate equal to the one just tried in the same slot) and stop the loop as soon as a value exceeds what is left of the target. That gives every answer exactly once without a set to remove duplicates afterward.
By Evin JohnPublished 9 min read
The problem, in plain terms
You get a list of positive whole numbers and a target. Choose some of the list's entries, each entry at most once, so that the chosen numbers add up to the target. Return every different choice. Two choices that contain the same numbers with the same counts are the same answer, even if they came from different positions in the list, and the order inside an answer does not matter.
list: 3 1 3 5 1 1
target: 8
answers:
1 1 1 5
1 1 3 3
3 5
picking by position gives 6 ways to reach 8:
1 1 1 5 (one way: all three 1s)
1 1 3 3 (three ways: any two of the three 1s)
3 5 (two ways: either 3)The gap between six position-level picks and three answers is the whole difficulty. A plain subset search counts positions, and the problem counts values. Questions worth asking first: are all numbers positive, can the list be empty, and does the order of the output matter. The early-stop trick below depends on positive numbers, so confirm that before you rely on it.
How it differs from the other combination sum problems
In the first Combination Sum problem the numbers are distinct and each may be reused any number of times, so the recursion stays on the same index after a pick. Here each entry is used once, so the recursion moves to the next index, and because values can repeat, you also need a rule against duplicate answers. Combination Sum III is the third variant: the pool is fixed to the digits 1 through 9 and the answer size is fixed too. Interviewers like this version because the duplicate rule is easy to get almost right.
Brute force: try every subset, then dedupe
The direct approach sorts the list, generates every combination of positions, keeps those with the right sum, and stores them as tuples in a set so that equal answers collapse into one. Sorting first matters: it makes [1, 3] and [3, 1] come out as the same tuple.
from itertools import combinations
def combination_sum_unique_brute(candidates, target):
nums = sorted(candidates)
found = set()
for size in range(1, len(nums) + 1):
for combo in combinations(nums, size):
if sum(combo) == target:
found.add(combo) # equal tuples collapse here
return [list(c) for c in found]This is O(2^n × n) time no matter how small the target is, and it builds every duplicate before throwing it away. It is still worth saying out loud in an interview, because it doubles as the reference you can test a faster version against.
The optimal approach: sorted backtracking with a same-depth skip
Think of the search as filling slots in an answer from left to right, always taking entries at higher positions than the last one taken. At one slot, the loop offers each remaining entry as the next number. If two entries have the same value, offering the second one at the same slot would produce exactly the answers the first one already produced, so skip it. The test is i > start and nums[i] == nums[i - 1]: the first copy at this depth is allowed, and later equal copies are skipped at this depth only. Deeper in the recursion the second copy is still reachable, which is how [1, 1, 3, 3] gets built.
def combination_sum_unique(candidates, target):
nums = sorted(candidates)
out, pick = [], []
def go(start, remaining):
if remaining == 0:
out.append(pick[:])
return
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue # same value already tried in this slot
if nums[i] > remaining:
break # sorted, so every later value is too big too
pick.append(nums[i])
go(i + 1, remaining - nums[i])
pick.pop()
go(0, target)
return outThe break is the second payoff of sorting. Once a value is larger than what remains, every value after it is at least as large, so the rest of the loop can be skipped. Negative numbers make this cut wrong. Zeros happen to work for a positive target, because they sort to the front and are offered before the remainder can reach 0, but a target of 0 returns only the empty answer. Say that the solution assumes positive values, or test zeros explicitly if they are allowed.
A second way to see it: choose how many copies
Instead of skipping equal neighbors, you can group equal values first and make one decision per distinct value: take it zero, one, two or more times, up to the number of copies available and the remaining target. Duplicates cannot appear because each distinct value is decided exactly once. Some people find this version easier to justify on a whiteboard, since there is no skip rule to defend.
function combinationSumUnique(candidates, target) {
const counts = new Map();
for (const x of candidates) counts.set(x, (counts.get(x) || 0) + 1);
const values = [...counts.keys()].sort((a, b) => a - b);
const out = [], pick = [];
function go(v, remaining) {
if (remaining === 0) { out.push(pick.slice()); return; }
if (v === values.length || values[v] > remaining) return;
const value = values[v];
const most = Math.min(counts.get(value), Math.floor(remaining / value));
for (let c = most; c >= 1; c--) { // take c copies of this value
for (let j = 0; j < c; j++) pick.push(value);
go(v + 1, remaining - c * value);
pick.length -= c;
}
go(v + 1, remaining); // take none of it
}
go(0, target);
return out;
}The numeric comparator in sort matters in JavaScript: the default sort compares values as strings and would put 10 before 9. On the worked example both functions return the same three answers. The order of answers differs between them, which is fine unless the interviewer asks for a specific order.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Every subset, set to dedupe | O(2^n × n) | O(A × L) for the set, plus each candidate tuple |
| Sorted backtracking with the skip | O(2^n × n) in the worst case, far less with the early stop | O(n) recursion and current pick, plus the output |
| Grouped counts | Same worst case, one branch per copy count | O(d) for d distinct values, plus the output |
The worst case stays exponential because the number of answers itself can be exponential. What the backtracking buys is that it never builds a duplicate and never continues down a branch that has already overshot. Say both things when the interviewer asks why the bound did not improve.
Edge cases to test
- An empty list, or a target smaller than every value: no answers.
- A list where one value repeats many times, such as five 2s with target 6: exactly one answer, [2, 2, 2].
- A single entry equal to the target.
- A target equal to the sum of the whole list, which has one answer that uses everything.
- Values given out of order, to check that the code sorts before skipping.
Common mistakes
- Writing the skip as i > 0 instead of i > start. That also blocks the second copy at deeper levels, so answers like [1, 1, 3, 3] disappear.
- Skipping equal values without sorting first. The skip only works when equal values sit next to each other.
- Recursing on i instead of i + 1, which reuses the same entry and turns this into the first Combination Sum problem.
- Appending pick instead of a copy of it, so every stored answer ends up as the same, later emptied list.
- Using continue instead of break for the too-large case. It is still correct, just slower, and the interviewer may ask why you did not stop.
How to explain it out loud
Fictional example
- Candidate
- If I treat the list as positions, the 1s give me three copies of the same answer. So I'll sort and make a rule: when I'm choosing the next number for one slot, I try each value only once.
- Candidate
- That's the check i greater than start and equal to the previous value. It only applies within one loop, so a second 1 can still go into the next slot.
- Candidate
- Because the list is sorted, once a value is bigger than what's left I can stop the loop. That assumes positive numbers, which you said is the case. Worst case it's still exponential, since the answer count can be.
Related problems
The same skip rule, with no target at all, lists every distinct subset in Subsets II. Applied to orderings rather than groups, it becomes the rule in Permutations II. When the pool is the digits 1 to 9 and the size is fixed, see Combination Sum III. If the question is only whether some split into equal-sum groups exists, read Partition to K Equal Sum Subsets.
Natively while you practice backtracking
Backtracking bugs hide in one line, like start versus 0, so it helps to replay how you reasoned. During practice, Natively (on Mac and Windows) can read a problem statement from a screenshot and write out an approach and code that you can set next to your own. Its transcript of a mock round shows whether you explained the skip before you typed it. More on AI help for coding interview practice.
Questions people ask
How do you solve Combination Sum II?
Sort the list and backtrack, moving to the next index after each pick. In each loop, skip a value equal to the one just tried at the same depth, and stop the loop once a value exceeds the remaining target.
How do you avoid duplicate combinations in Combination Sum II?
After sorting, skip nums[i] when i is greater than the loop's start and nums[i] equals nums[i - 1]. That tries each value once per slot while still letting a second copy go into a later slot.
What is the time complexity of Combination Sum II?
The worst case is exponential, O(2^n × n), because the number of answers can be exponential. Sorting, the duplicate skip and the early stop cut the search a lot in practice.
What is the difference between Combination Sum and Combination Sum II?
In Combination Sum the values are distinct and each can be reused, so the recursion stays on the same index. In Combination Sum II each entry is used once and values can repeat, so you move to the next index and need a duplicate skip.
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.
