InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Backtracking

Combination Sum II

medium Original ↗ 00:00

Problem

You are given an array candidates of positive integers, which may contain duplicates, and a positive integer target. Return every unique combination of candidates that sums to exactly target, where each array element may be used at most once. Two occurrences of the same value are distinct elements (each usable once), but combinations that are equal as multisets count as one: the output must not contain the same combination twice. Combinations may be returned in any order.

Examples

  • candidates = [10,1,2,7,6,1,5], target = 8[[1,1,6],[1,2,5],[1,7],[2,6]] — note [1,7] appears once even though there are two 1s that could pair with 7.
  • candidates = [2,5,2,1,2], target = 5[[1,2,2],[5]] — three 2s exist but a combination may use at most the multiplicities present.
  • candidates = [3,3], target = 6[[3,3]] — both copies used, each once.

Constraints

  • 1 <= len(candidates) <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

With up to 100 elements, enumerating all 2^100 subsets is infeasible. The duplicate values are what let you prune the search space.

Think about it first

Hint 1 This differs from Combination Sum in two ways: each element is single-use (recurse past it, not on it), and equal values exist. Which of the two causes duplicate output?
Hint 2 Sort the array. Now equal values sit together. If at some tree depth you start a branch with the first `1` and later start a sibling branch with the second `1`, those two branches generate identical combination sets. When is choosing a duplicate value safe, and when is it redundant?
Hint 3 In the loop over choices at one recursion level, skip candidates[i] when i > start and candidates[i] == candidates[i-1]: using a duplicate is fine when it directly follows its twin in the path (deeper level), but starting a fresh sibling branch with it repeats work. Add the sorted-overshoot break and the search collapses.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug