InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Backtracking

Combination Sum

medium Original ↗ 00:00

Problem

You are given an array candidates of distinct positive integers and a positive integer target. Return every unique combination of candidates whose values sum to exactly target. The same candidate may be used any number of times within one combination. Two combinations are considered the same if they use the same values with the same multiplicities, regardless of order — so your answer must not contain duplicates like [2,3] and [3,2]. Combinations may be returned in any order.

Examples

  • candidates = [2,3,6,7], target = 7[[2,2,3],[7]]2+2+3 = 7 (reusing 2 twice) and 7 alone both work.
  • candidates = [2,3,5], target = 8[[2,2,2,2],[2,3,3],[3,5]] — three distinct multisets reach 8.
  • candidates = [2], target = 1[] — every candidate exceeds the target, so no combination exists.

Constraints

  • 1 <= len(candidates) <= 30
  • 2 <= candidates[i] <= 40, all values distinct
  • 1 <= target <= 40
  • The number of unique combinations is guaranteed to be fewer than 150.

The small target and the “fewer than 150 answers” guarantee indicate that an exponential search is expected. The task is to prune it so you never build the same combination twice.

Think about it first

Hint 1 Every candidate is at least 2, so a combination can contain at most target/2 numbers. Think of building a combination one number at a time, subtracting from the remaining target as you go.
Hint 2 How do you avoid generating both [2,3] and [3,2]? Force combinations to be built in non-decreasing candidate order: once you move past a candidate, never pick it again in that branch.
Hint 3 Recurse with (start index, remaining). At index i you may pick candidates[i] again (stay at i, since reuse is allowed) or skip ahead. When remaining hits 0, record a copy of the current path; when it goes negative, backtrack. Sorting first lets you cut a whole branch as soon as one candidate overshoots.

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