15% off all plans & roadmaps Use code

See plans

Combination Sum II

Updated

TL;DR: Find every unique group of numbers from a list with duplicates that adds up to a target, using each position once. Sort the list, backtrack, and skip a value that repeats the previous one at the same depth.

Problem

You get an array of candidate numbers candidates and a number target. Return every unique combination of candidates whose values add up to target.

Each element of candidates can be used at most once in a combination. The array may contain duplicate values, but the answer must not contain duplicate combinations. The combinations may be returned in any order.

Example 1

Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: [
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

Example 2

Input: candidates = [2,5,2,1,2], target = 5
Output: [
[1,2,2],
[5]
]

Constraints

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

Constraints that matter

  • candidates.length up to 100 means a full power set of 2^100 subsets is impossible, so you must prune.
  • Every value is at least 1, so the running sum only grows. Once it passes target, you can stop that branch.
  • target is at most 30, so a combination holds at most 30 numbers. Recursion depth never exceeds 30 even with 100 candidates.
  • Values are small and positive, so sorting is cheap and lets you break out of a loop as soon as one value is too big.
  • Duplicates are allowed in the input, so the answer needs a rule that stops two equal values from producing the same combination twice.

View on LeetCode

Hints

Hint 1

This is backtracking over a decision tree.

Hint 2

Try every subset of the array.

Solution

Intuition

This is backtracking over a decision tree. You build a combination one number at a time, and you undo the last choice when a branch is finished. Each recursive call picks the next number from the part of the array that is still available.

Picture a row of sorted coin jars where two jars hold identical coins. At each step you pick one jar to dip into, and once you have looked through a jar you never open another identical jar at that same step, because it would only show you the same handful again.

The twist is duplicates. With [1, 1, 6] and target 8, the first 1 plus 6 gives the same combination as the second 1 plus 6. If the code treats the two ones as different, the same multiset shows up twice.

Sort the array first so equal values sit side by side. At any single call, the loop should try each distinct value once as the next pick. If candidates[i] equals candidates[i-1] and i is past the first index the loop started from, the previous iteration already explored every combination that starts with that value from this position. Trying it again can only repeat work.

The check is i > start, not i > 0. A deeper call may legitimately pick the second 1 after the first 1 was already chosen higher in the tree. That is how [1, 1, 6] gets built. The skip applies to siblings in one loop, not to parent and child.

Sorting also gives a free pruning rule. If candidates[i] is bigger than the remaining target, every later value is bigger too, so you break rather than continue.

Watch the pattern animation

Worked example

Input: candidates = [1, 1, 1, 1], target = 4
Output: [[1, 1, 1, 1]]
Explanation: All four ones are needed to reach 4, so the only valid group is [1, 1, 1, 1]. Four different positions could supply any single 1, yet the answer must list the combination once. This input is a good test of duplicate handling.

Approach 1: Brute force: all subsets plus a set

Try every subset of the array. For each one, add up the values and keep it when the sum equals target. Because the input has duplicates, the same multiset can come from different positions, so store each found combination in a set to remove repeats.

Sort the array first so that every subset is built in ascending order. Then two subsets with the same values produce the identical list, and the set can compare them directly. Stop a branch when the sum passes target, since all values are positive.

Steps

  1. Sort candidates ascending.
  2. Define pick(i, total, path) that decides whether to take candidates[i].
  3. If total == target, record path when it is not already in the set, then return.
  4. If i reached the end or total > target, return.
  5. Take candidates[i]: push it, recurse with i + 1, then pop it.
  6. Skip candidates[i]: recurse with i + 1 and the same path.
  7. Call pick(0, 0, []) and return the recorded combinations.

Dry run

Take [1, 1, 1, 1] with target 4. The sort changes nothing.

  • Each of the four positions is either taken or skipped, so the recursion visits subsets of every size.
  • Subsets of size 0 to 3 have sums 0 to 3, all below 4, so none is recorded.
  • Only the branch that takes all four ones reaches total == 4. It records [1, 1, 1, 1].
  • The set is empty at that moment, so the combination is added.

The result is [[1, 1, 1, 1]]. With only one match the set never has to reject anything here. On [1, 1, 6] with target 8 it would reject the second [1, 6] style repeat.

Complexity

TimeO(2^n * n)
SpaceO(n) recursion, plus the set of stored combinations

Here n is the length of candidates. Each element is taken or skipped, so the recursion tree has up to 2^n leaves. Each recorded hit costs O(n) to copy and to hash or compare. The recursion depth is n, and the set holds only the unique answers, which are part of the output.

PythonTested in our runner

from typing import List

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        seen = set()
        result = []

        def pick(i, total, path):
            if total == target:
                key = tuple(path)
                if key not in seen:
                    seen.add(key)
                    result.append(list(path))
                return
            if i == len(candidates) or total > target:
                return
            # take candidates[i]
            path.append(candidates[i])
            pick(i + 1, total + candidates[i], path)
            path.pop()
            # skip candidates[i]
            pick(i + 1, total, path)

        pick(0, 0, [])
        return result
Combination Sum pattern infographic for Combination Sum II

Solution pattern

Combination Sum

Part of Backtracking Patterns

Approach 2: Sorted backtracking with sibling skipOptimalCombination Sum

What's slow: the brute force builds every duplicate combination and only throws it away at the end. With many equal values it explores the same subtree again and again. It also keeps walking down a branch after the remaining target has dropped below every available number.

The insight that fixes it: sort, and let each call loop over the next pick. The loop moves forward from start, so each element is used once and order inside a combination never varies.

If i > start and candidates[i] == candidates[i-1], skip. The earlier sibling already covered every combination that begins with that value here. Break out of the loop when candidates[i] > remaining, since later values are at least as large. Duplicates are never generated, so no set is needed.

Why it is correct. At each call, the loop tries every distinct value once as the next pick, so every multiset that starts from this position is reached. When candidates[i] equals candidates[i-1] and i is past start, the earlier sibling already explored all combinations beginning with that value here. Skipping the repeat therefore loses nothing and only removes duplicate work.

Steps

  1. Sort candidates ascending.
  2. Define dfs(start, remaining) with a shared path list.
  3. If remaining == 0, copy path into the result and return.
  4. Loop i from start to the end of the array.
  5. If candidates[i] > remaining, break, because the array is sorted.
  6. If i > start and candidates[i] == candidates[i-1], continue to skip the repeated sibling.
  7. Push candidates[i], call dfs(i + 1, remaining - candidates[i]), then pop it.

Dry run

Trace [1, 1, 1, 1] with target 4. The final frame in the table shows the combination being recorded, and every other row shows a skip or a return.

StepCall (start, remaining)Loop iActionPath
1dfs(0, 4)0pick 1, go deeper[1]
2dfs(1, 3)1pick 1, go deeper[1,1]
3dfs(2, 2)2pick 1, go deeper[1,1,1]
4dfs(3, 1)3pick 1, go deeper[1,1,1,1]
5dfs(4, 0)noneremaining is 0, record a copy[1,1,1,1]
6back in dfs(3, 1)4loop ends, pop[1,1,1]
7back in dfs(2, 2)33 > start 2 and equals previous, skip[1,1,1]
8back in dfs(1, 3)2, 3both skipped, pop[1]
9back in dfs(0, 4)1, 2, 3all skipped, pop[]

The result is [[1, 1, 1, 1]], recorded once. The brute force touched all 16 subsets. This version makes 5 calls and skips the rest in a handful of checks.

Complexity

TimeO(2^n) worst case, with a per-answer copy cost
SpaceO(min(n, target)) for the path and recursion, excluding the output

Here n is the length of candidates. Sorting costs O(n log n). The recursion tree has at most one node per distinct sub-multiset whose sum stays within target, and that count is bounded by the 2^n subsets.

Each recorded answer costs O(length) to copy. The path holds at most min(n, target) numbers. Every value is at least 1 and the remaining target must stay non-negative.

PythonTested in our runner

from typing import List

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        result = []
        path = []

        def dfs(start, remaining):
            if remaining == 0:
                result.append(list(path))
                return
            for i in range(start, len(candidates)):
                # sorted, so every later value is too big as well
                if candidates[i] > remaining:
                    break
                # skip a repeated value among siblings at this depth
                if i > start and candidates[i] == candidates[i - 1]:
                    continue
                path.append(candidates[i])
                dfs(i + 1, remaining - candidates[i])
                path.pop()

        dfs(0, target)
        return result

Common mistakes

  • Writing if i > 0 and candidates[i] == candidates[i-1]: continue instead of i > start. This forbids using two equal values together, so [1, 1, 6] is lost. Compare against start, not 0.
  • Skipping duplicates without sorting first. Equal values are not adjacent, so candidates[i] == candidates[i-1] misses repeats. Call sort before the first dfs.
  • Recursing with dfs(i, ...) instead of dfs(i + 1, ...). That is the Combination Sum I rule and lets one element be reused. Pass i + 1.
  • Appending path directly with result.append(path). The list is mutated later and every stored answer ends up empty. Append a copy such as list(path).
  • Using continue where the too-big check needs break. It still returns the right answer but scans every remaining value in every call. Break, because the array is sorted.
  • Checking remaining == 0 only after the loop starts, or never returning after recording. Return as soon as remaining == 0 so you do not try to add more numbers to a finished combination.

Edge cases

  • candidates = [1], target = 1 returns [[1]], the smallest valid input.
  • candidates = [2], target = 1 returns an empty list because no combination reaches the target.
  • candidates = [1, 1, 1, 1], target = 4 returns one combination, [[1, 1, 1, 1]], not four copies.
  • candidates = [2, 5, 2, 1, 2], target = 5 returns [1, 2, 2] and [5]. Three equal 2s must not make [2, 2, 1] appear in more than one form.
  • candidates = [1, 2, 3], target = 30 returns an empty list. The sum of all values is 6, so every branch dies.
  • One hundred ones with target = 30 has a single answer with thirty ones. The skip rule keeps the search small, while the brute force would blow up here.

Follow-ups interviewers ask

What changes if each number may be used any number of times, as in Combination Sum I?
Recurse with dfs(i, ...) so the same index can be picked again. If the input has no duplicates you need no skip rule. If it does have duplicates, dedupe the array first, or keep the skip check.
How would you do this without relying on the skip check, for example by counting values?
Sort, then build a list of (value, count) pairs. At each pair, choose how many copies to take, from 0 up to its count, and move to the next pair. Every combination is a unique choice of counts, so duplicates cannot occur.
Can you cut work further for large inputs?
Yes. Precompute suffix sums and return early if the remaining numbers cannot reach the remaining target. You can also stop when the smallest remaining value exceeds the target. Neither changes the worst-case bound, but both trim real runs.

Combination Sum II FAQ

What is the time complexity of Combination Sum II?

The bound you can prove is O(2^n), where n is the number of candidates, plus the cost of copying each answer. Sorting adds O(n log n). In practice pruning on the remaining target and skipping repeated siblings make it far smaller. Since target is at most 30, each path has at most 30 numbers.

Why use backtracking for Combination Sum II?

You must list every valid combination, not count them or find one. That forces you to explore choices and undo them. Backtracking builds one combination in a shared list and reverts the last pick when a branch ends, which keeps memory small and lets you prune early.

Why sort the array first in LeetCode 40?

Sorting puts equal values next to each other, so comparing candidates[i] with candidates[i-1] detects a repeat. It also lets you break out of the loop as soon as a value is greater than the remaining target.

Why is the skip condition i > start and not i > 0?

The check should only skip a repeat among siblings in one loop. A deeper call starts at start = i + 1, so its first element is allowed even if it equals the value picked above. Using i > 0 would block [1, 1, 6].

Can Combination Sum II be solved in O(1) extra space?

No. The recursion stack and the current path grow with the number of picked values, up to min(n, target). You can drop the set used in the brute force, but you cannot remove the path and the stack.

How is Combination Sum II different from Combination Sum I?

In Combination Sum I every number can be reused and the input has distinct values. Here each element is used once and the input can repeat values. So you recurse on i + 1 instead of i, and you add the sibling skip rule to avoid duplicate combinations.

Asked at

See which companies ask this — Pro

Practise it