InterviewPrepKit

Home / Coding / Backtracking

Combination Sum II

medium Original β†—
Solving tips
  • Two differences from Combination Sum I drive the solution: each element is single-use (recurse with i+1) and duplicate values must not spawn duplicate combinations.
  • Sort first, then in the per-level loop skip candidates[i] when i > start and candidates[i] == candidates[i-1]: this suppresses duplicate sibling branches while still allowing repeated values along a path.
  • Use i > start (not i > 0) for the skip, or you wrongly drop valid answers like [1,1,6] where a value repeats within one path.
  • Worst case is O(2^n) time with O(n) space; the sorted break plus duplicate-skip prune aggressively so it never approaches 2^100.

Problem

You are given an array candidates of positive integers β€” duplicates allowed this time β€” 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 different elements (each usable once), but combinations that read the same as multisets count as one: the output must not contain the same combination twice. Any order of combinations is fine.

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, anything that enumerates all 2^100 subsets is hopeless β€” the duplicate values are what let you collapse 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 actually 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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.