TRT
Sign in
mediumCoreLeetCode#backtracking#skip duplicates

Combination sum II

Find every unique combination that sums to a target when each candidate may be used once and the input contains duplicates.

The Runtime Theory Team1 min read
Taught inBacktracking basicsPro — members onlyBacktracking builds a solution one choice at a time, explores each choice recursively and undoes it afterwards. Pruning dead ends early is what makes it practical.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

incandidates = [10, 1, 2, 7, 6, 1, 5], target = 8

out[[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]

incandidates = [2, 5, 2, 1, 2], target = 5

out[[1, 2, 2], [5]]

incandidates = [1], target = 2

out[]

Given candidates that may contain duplicates and a target, return all unique combinations that sum to the target, using each candidate at most once.

Before you code

Two equal candidates at the same level of the search lead to identical branches. Generating everything and deduplicating at the end works, but wastes most of the time.

Hints

  1. Sort the candidates so equal values are adjacent.
  2. Recurse with i + 1, because each candidate can be used once.
  3. In the loop, skip candidates[i] when i > start and it equals candidates[i - 1]: that value was already tried at this level.
  4. Break once a candidate exceeds the remaining sum.

Production & complexity notes

When solving Combination sum II on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Backtracking basics to reinforce the underlying pattern.

What it practices

The choose, explore, unchoose pattern and pruning, from Backtracking basics.

Not started

Sign in to save your learning progress.

Sign in to save