40. Combination Sum II
mediumFind every combination summing to a target when the candidates may contain duplicates and each candidate can be used at most once. The dedup-by-index pattern from Subsets II applied to a sum-target backtrack.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations.
Constraints
1 <= candidates.length <= 1001 <= candidates[i] <= 501 <= target <= 30
Examples
Example 1
candidates = [10,1,2,7,6,1,5], target = 8[[1,1,6],[1,2,5],[1,7],[2,6]]Example 2
candidates = [2,5,2,1,2], target = 5[[1,2,2],[5]]Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Sort candidates so duplicates are adjacent.
Hint 2
Each number can be used once, so the recursive call uses start = i + 1.
Hint 3
Dedup rule: at iteration index i > start, skip if candidates[i] == candidates[i-1]. The 'i > start' (not 'i > 0') matters — we still want the first copy at this depth.
Hint 4
Prune: break out of the loop once candidates[i] > remaining (because the array is sorted).
Solution approach
Reveal approach
Sort candidates ascending. Backtrack with (start, remaining, path). Base: remaining == 0 -> snapshot path. Recursive: for i from start while i < n and candidates[i] <= remaining: skip if i > start and candidates[i] == candidates[i-1] (this is the dedup); push candidates[i], recurse(i + 1, remaining - candidates[i], path), pop. Two important differences from Combination Sum: recursive call is i + 1 (each candidate used at most once), and the i > start dedup skip prevents duplicate combinations even though the input has duplicates. Time is O(2^n * n) worst case (every subset); the prune + dedup typically does far better. Space is O(target) recursion depth.
Complexity
- Time
- O(2^n * n)
- Space
- O(target)
Related patterns
- backtracking
- recursion
- duplicates-handling
Related problems
- 39. Combination Sum
- 216. Combination Sum III
- 90. Subsets II
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Microsoft
- Bloomberg
- Apple
More Recursion practice problems
- 10. Regular Expression Matching
- 17. Letter Combinations of a Phone Number
- 37. Sudoku Solver
- 38. Count and Say
- 39. Combination Sum
- 44. Wildcard Matching
- 46. Permutations
- 47. Permutations II