Skip to the solution
MediumDSA12 min read

How do you solve the Combination Sum problem?

907 views

The problem

Question presented to candidate: "Given a list of distinct positive integers candidates and a target, return every unique combination of candidates that sums to the target. Each number may be used any number of times. Code it in Python."

What a strong answer should cover:

  • Backtracking with a running remaining amount: choose a candidate, recurse with remaining - x, un-choose; record when remaining is 0.
  • The start index: recurse with i (reuse allowed) and never go back to smaller indices, so each combination appears once instead of in every order.
  • Pruning: sort the candidates and break as soon as a candidate exceeds remaining.
  • Complexity is exponential in target / smallest candidate; extra space is the recursion depth, at most target / smallest candidate.
  • The variants: Combination Sum II (each number once, duplicates in input: i + 1 plus the skip rule) and counting combinations with coin-change DP.
  • Python details: sorted() returns a new list (the input is left alone), record path[:], and the recursion depth is up to target / smallest candidate, which can reach the default limit of 1000 frames.

Clarifying questions expected:

  • Are the candidates distinct and all positive?
  • May a number be used more than once?
  • Does the order of the combinations (or within a combination) matter?

Code / implementation expected: Yes โ€” a backtracking function in Python returning list[list[int]], with the start index and the sort-and-break pruning.

  • dsa
  • backtracking

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonCombination Sum: results, and calls with vs without pruning
PythonStart-index bug, Combination Sum II, and a DP count check

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 54 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

Maximum subarray (Kadane) vs divide-and-conquer โ€” proof of correctness?

Continue