LeetCode #40 Medium

Combination Sum II

Combination Sum II is LeetCode 40 (Medium). You get an array candidates that may contain duplicate values and a positive target. Return every unique combination of candidates that adds up to target.

  • Each array element may be used at most once in a combination.
  • Two combinations that hold the same values are the same answer, whatever order they are in, so the list must not contain one twice.

The target is at most 30, so a backtracking search that stops early stays small even with 100 candidates.

Constraints
  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30
backtrackingrecursionarray
Open on LeetCode ↗
02

Intuition

Sort the array, then build each combination from left to right, choosing one index per depth. Equal values now sit next to each other, which makes the repeats easy to see.

  • Same depth, same value: if two equal values are both offered as the next choice, the second copy can only build lists the first copy already built. Skip a value that equals its left neighbour, unless it is the first option at this depth.
  • Deeper down: the second copy may still be taken right after the first, so [1, 1, 6] is still found.
How to spot this pattern

The question wants every combination listed, not a count, so the answer is a search that builds lists and undoes choices. Duplicates in the input plus "no repeated combinations" is the signal for sort-then-skip.

03

Approach

Try it first

Before reading on, sort [2, 1, 3, 1] and list the combinations that make 4 by hand. Which branch would build [1, 3] a second time, and what single comparison stops it?

1

Sort the candidates

Sort once at the start. It puts equal values side by side, so a repeat is found by comparing with the left neighbour, and it puts small values first, so the loop can stop at the first value that is too big.

2

Search with a start index

Write dfs(start, remain): try each index i from start to the end as the next number, with remain still to reach. Starting at start means the numbers in a combination always come in sorted order, so [1, 3] is never also built as [3, 1].

3

Skip repeats at the same depth

Inside the loop, skip i when i > start and candidates[i] == candidates[i - 1]. The i > start part keeps the first copy at each depth, so a second copy can still be used one depth further down, right after the first.

4

Stop early, record, and undo

If candidates[i] > remain, break: the array is sorted, so no later value fits either. Otherwise append it, call dfs(i + 1, remain - candidates[i]), then pop it. When remain reaches 0, save a copy of the path, since the list itself keeps changing.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
▶3 candidates.sort()
▶4 res, path = [], []
▶5 
▶6 def dfs(start: int, remain: int) -> None:
▶7 if remain == 0:
▶8 res.append(path[:])
▶9 return
▶10 for i in range(start, len(candidates)):
▶11 if i > start and candidates[i] == candidates[i - 1]:
▶12 continue
▶13 if candidates[i] > remain:
▶14 break
▶15 path.append(candidates[i])
▶16 dfs(i + 1, remain - candidates[i])
▶17 path.pop()
▶18 
▶19 dfs(0, target)
▶20 return res
1st11234 leftanswersnone yetsorted: 1 1 2 3, target 4
candidates[1, 1, 2, 3]after sorting
target4
Sorting puts equal values next to each other, so a repeat can be spotted by looking one tile to the left. Each row below is one depth of the search: the row says which number of the combination is being chosen.
1st11234 left2nd11233 leftanswersnone yettake 1 → 3 left
path[1]
remain3
Take the 1 at index 0 as the 1st number. The next depth may only use indices after 0, so this element cannot be taken twice; its row starts one tile to the right.
1st11234 left2nd11233 left3rd11232 leftanswersnone yettake 1 → 2 left
path[1, 1]
remain2
Take the 1 at index 1 as the 2nd number. The next depth may only use indices after 1, so this element cannot be taken twice; its row starts one tile to the right.
1st11234 left2nd11233 left3rd11232 leftanswers112take 2 → 1 + 1 + 2 = 4 → save it
saved[1, 1, 2]
The last 2 uses up exactly what was left, so the picks [1, 1, 2] are an answer. A copy is saved, because the path list keeps changing as the search backs up and tries other picks.
1st11234 left2nd11233 left3rd1123too big2 leftanswers1123 is more than 2 left → stop this row
candidate3
remain2
The array is sorted, so every tile to the right of this 3 is at least as big. None of them fits in 2, so the loop ends here and the search goes back up a depth.
1st11234 left2nd11233 left3rd11231 leftanswers112take 2 → 1 left
path[1, 2]
remain1
Take the 2 at index 2 as the 2nd number. The next depth may only use indices after 2, so this element cannot be taken twice; its row starts one tile to the right.
1st11234 left2nd11233 left3rd1123too big1 leftanswers1123 is more than 1 left → stop this row
candidate3
remain1
The array is sorted, so every tile to the right of this 3 is at least as big. None of them fits in 1, so the loop ends here and the search goes back up a depth.
1st11234 left2nd11233 leftanswers11213take 3 → 1 + 3 = 4 → save it
saved[1, 3]
The last 3 uses up exactly what was left, so the picks [1, 3] are an answer. A copy is saved, because the path list keeps changing as the search backs up and tries other picks.
1st11repeat234 leftanswers11213another 1 at the 1st pick → skip
index1same value as index 0
remain4
This 1 equals the tile to its left, and it is not the first option in this row. The earlier 1 was already tried as the 1st number with everything after it, so this copy could only rebuild the same lists.
1st11234 left2nd11232 leftanswers11213take 2 → 2 left
path[2]
remain2
Take the 2 at index 2 as the 1st number. The next depth may only use indices after 2, so this element cannot be taken twice; its row starts one tile to the right.
1st11234 left2nd1123too big2 leftanswers112133 is more than 2 left → stop this row
candidate3
remain2
The array is sorted, so every tile to the right of this 3 is at least as big. None of them fits in 2, so the loop ends here and the search goes back up a depth.
1st11234 left2nd11231 leftanswers11213take 3 → 1 left
path[3]
remain1
Take the 3 at index 3 as the 1st number. The next depth may only use indices after 3, so this element cannot be taken twice; its row starts one tile to the right.
1st11234 left2nd11231 leftanswers11213no numbers left after this → back up
remain1still needed
The last pick was the final element, so this row has nothing to offer and 1 is still missing. This branch ends without an answer.
1st11234 leftanswers11213done → 2 combinations saved
result[[1, 1, 2], [1, 3]]
Every branch has been tried. Each answer appears once, because a repeated value was never offered twice at the same depth.
05

Common pitfalls

Comparing with the neighbour without the i > start guard

✗ Wrong
if i > 0 and candidates[i] == candidates[i - 1]:
    continue
✓ Right
if i > start and candidates[i] == candidates[i - 1]:
    continue

With i > 0, the second 1 is skipped even when it is the first option one level down, right after taking the first 1. On [1, 1, 6] with target 8 the answer [1, 1, 6] is lost and nothing is returned. The mistake hides because it removes answers instead of adding repeats.

Recursing with i instead of i + 1

✗ Wrong
dfs(i, remain - candidates[i])
✓ Right
dfs(i + 1, remain - candidates[i])

Passing i lets the same element be taken again, which is the rule of Combination Sum (39). On [2] with target 4 it returns [[2, 2]] when the answer is [].

Removing repeats with a set afterwards

✗ Wrong
seen = set()
# build every subset that sums to target,
# then add tuple(path) to seen
✓ Right
if i > start and candidates[i] == candidates[i - 1]:
    continue

The search still walks every repeated branch before the set throws the copies away. On thirty 1s with target 15, it builds over 150 million lists to keep a single one, [1] * 15; the skip builds just one.

06

Edge cases

The target is smaller than every candidate, e.g. [5, 6], target 3

The first value already fails candidates[i] > remain, so the loop breaks at once and [] is returned.

07

Complexity

Time
O(2^n · n)
Space
O(n)
Each element is either in a combination or not, so at most 2^n paths, and saving one copies up to n values. The small target and the early break keep the real search far smaller. Space is the recursion depth and the path, not counting the output.
08

Combination Sum II FAQ

How is it different from Combination Sum (39)?

In Combination Sum the values are distinct and each can be reused, so the search recurses with i. Here each element is used once (recurse with i + 1) and equal values may repeat, so the same-depth skip is needed.

Why is skipping the second copy safe?

At one depth, both copies would become the same next number, and the indices after the second copy are a subset of the indices after the first. So any list built from the second copy can also be built from the first. Nothing is lost, only the repeat.

What if only the number of combinations is needed?

The same search can return a count instead of lists. With a target this small, a DP over (index, remaining sum) that treats each run of equal values as one group also works, choosing how many copies of the value to take.