Skip to content
mlmentorship

Combination Sum

Combine same-index reuse with a nondecreasing choice boundary and positive remaining-target decrease, then switch to finite occurrences or count-only DP.

Published · 22 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Combination Sum

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. An integer list candidates and an integer target. Output. Return every distinct combination of positive candidate values whose sum equals target. Rules. Reuse is unlimited. Reordering the same values does not create a new combination. The reference ignores duplicate and nonpositive candidates; it does not solve unrestricted signed combinations. Leave the input unchanged. Target zero returns [[]]; a negative target returns []. Example. For candidates = [2, 3, 6, 7] and target = 7, return [[2, 2, 3], [7]]. [2, 3, 2] is not an additional answer because it repeats the same value combination.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Carry the remaining target, reuse the current sorted index, and break when the next choice is too large.

Problem trace

Reusing a value is allowed; returning to an earlier choice index is not

Worked example: reuse a value without returning to an earlier choice indexFor candidates (2,3), path (2,2,3) is allowed. Path (3,2,2) would duplicate the same combination and requires a backward index move.A permitted choice order emits eachmembership once001Allowed order: emit this membership.100Backward order: duplicate membership;do not emit.
Read it this way: For candidates (2,3), path (2,2,3) is allowed. Path (3,2,2) would duplicate the same combination and requires a backward index move. Why is repeating index zero allowed while returning from index one to zero is not?
Full interview answer 22 min read

List the distinct value combinations that reach an exact target, allowing each positive candidate to be reused.

Problem

Input. An integer list candidates and an integer target.

Output. Return every distinct combination of positive candidate values whose sum equals target.

Rules. Reuse is unlimited. Reordering the same values does not create a new combination. The reference ignores duplicate and nonpositive candidates; it does not solve unrestricted signed combinations. Leave the input unchanged. Target zero returns [[]]; a negative target returns [].

Example. For candidates = [2, 3, 6, 7] and target = 7, return [[2, 2, 3], [7]]. [2, 3, 2] is not an additional answer because it repeats the same value combination.

Picture

For [2,3,6,7] and target seven:

PathstartremainingNext action
[]07Choose 2
[2]05Reuse 2
[2,2]03Try 2, then 3
[2,2,2]01Break because 2 is too large
[2,2,3]10Copy a solution
[7]30Copy the other solution

Keep sum(path) + remaining == target. start is the lowest eligible choice index, not the path length. Passing the same index permits another copy. Never decreasing it prevents reordered duplicates such as [3,2,2].

Each positive choice strictly reduces remaining. Once a sorted choice exceeds the remainder, every later choice does too: break the loop.

Reuse append, recurse, undo. Pop after each recursive return, but copy a successful path before later mutations change it.

The call nodes show remaining targets; labels below them show start. Each arrow subtracts the chosen value.

Problem trace

Reusing a value is allowed; returning to an earlier choice index is not

Input and goalReturn combinations that add to a target. A value may be used more than once.
Initialize sorted choicesPositive unique choices are [2,3,6,7]. Call choose(0,7) with an empty path.
start 07
Original path, start and remaining stack
[]active call07
inputcandidates = [2,3,6,7], target = 7columnspath | start | remainingactionchoices = [2,3,6,7]answer[]
active call
(0, 0)
input
candidates = [2,3,6,7], target = 7
columns
path | start | remaining

Recognize it
Use this pattern when combinations must sum to a target, order should not duplicate answers, and the same positive candidate may be selected repeatedly.
Keep true
Every path is nondecreasing by choice index, sum(path) + remaining equals the original target, and choose(start, remaining) may use only start or later indices; remaining zero is exactly a solution.
Reuse it
For reusable combination search, carry a decreasing feasibility measure and a nondecreasing choice boundary; sorted positive choices turn the first oversized option into a safe loop break.
Positive unique choices are [2,3,6,7]. Call choose(0,7) with an empty path. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why may 2 be chosen twice, but not after the path has advanced to 3?
Reference drawing

Problem trace

Reusing a value is allowed; returning to an earlier choice index is not

Worked example: reuse a value without returning to an earlier choice indexFor candidates (2,3), path (2,2,3) is allowed. Path (3,2,2) would duplicate the same combination and requires a backward index move.A permitted choice order emits eachmembership once001Allowed order: emit this membership.100Backward order: duplicate membership;do not emit.
Execution trace
Input and goalReturn combinations that add to a target. A value may be used more than once.
Initialize sorted choicesPositive unique choices are [2,3,6,7]. Call choose(0,7) with an empty path.
start 07
Original path, start and remaining stack
[]active call07
inputcandidates = [2,3,6,7], target = 7columnspath | start | remainingactionchoices = [2,3,6,7]answer[]
active call
(0, 0)
input
candidates = [2,3,6,7], target = 7
columns
path | start | remaining

Recognize it
Use this pattern when combinations must sum to a target, order should not duplicate answers, and the same positive candidate may be selected repeatedly.
Keep true
Every path is nondecreasing by choice index, sum(path) + remaining equals the original target, and choose(start, remaining) may use only start or later indices; remaining zero is exactly a solution.
Reuse it
For reusable combination search, carry a decreasing feasibility measure and a nondecreasing choice boundary; sorted positive choices turn the first oversized option into a safe loop break.
Positive unique choices are [2,3,6,7]. Call choose(0,7) with an empty path. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why may 2 be chosen twice, but not after the path has advanced to 3?
Read it this way: For candidates (2,3), path (2,2,3) is allowed. Path (3,2,2) would duplicate the same combination and requires a backward index move. Why is repeating index zero allowed while returning from index one to zero is not?

Code

def combination_sum(candidates: list[int], target: int) -> list[list[int]]:
   choices = sorted({num for num in candidates if num > 0})
   answer: list[list[int]] = []
   path: list[int] = []

   def choose(start: int, remaining: int) -> None:
      if remaining == 0:
         answer.append(path.copy())
         return

      for index in range(start, len(choices)):
         num = choices[index]
         if num > remaining:
            break
         path.append(num)
         choose(index, remaining - num)
         path.pop()

   choose(0, target)
   return answer

Cost: Exponential time in the worst case and call-stack space when the smallest choice is 1.

For inputs and positive unique values, normalization costs expected . With positive target, depth is at most when choices exist. Working storage includes those choices and the active path; retained output additionally stores every copied answer element.

Change Reuse or the Answer Type

Start from combination_sum. Preserve the remainder invariant while making the changed multiplicity or output contract explicit.

  1. Consume each input position once.

    New task: Values are finite occurrences, not reusable denominations.

    Picture and change: Keep duplicate positive occurrences. Recurse with index + 1, and skip equal siblings only at the same decision depth. Equal values at deeper indices can still be used together.

    Code: Complete replacement, retaining positive filtering:

    def combination_sum_once(candidates, target):
       choices = sorted(value for value in candidates if value > 0)
       answer, path = [], []
    
       def choose(start, remaining):
          if remaining == 0:
             answer.append(path.copy())
             return
          for index in range(start, len(choices)):
             value = choices[index]
             if value > remaining:
                break
             if index > start and value == choices[index - 1]:
                continue
             path.append(value)
             choose(index + 1, remaining - value)
             path.pop()
    
       choose(0, target)
       return answer

    Check: [2,2,3], target four gives [[2,2]]. [2,3], target four gives [], unlike unlimited reuse.

    Use when: Each occurrence is consumable. Depth is at most the number of positive positions, but enumeration and output can still be exponential.

  2. Count reusable combinations.

    New task: Return only the number of value combinations.

    Picture and change: Initialize one empty construction at subtotal zero. Process denominations outside and subtotals upward: the current denomination may repeat, but earlier denominations cannot be reordered afterward.

    Code: Complete replacement:

    def count_combinations(candidates, target):
       if target < 0:
          return 0
       counts = [0] * (target + 1)
       counts[0] = 1
       for value in sorted({value for value in candidates if value > 0}):
          for subtotal in range(value, target + 1):
             counts[subtotal] += counts[subtotal - value]
       return counts[target]

    Check: [2,3,6,7], target seven gives two; target zero gives one. [1,2], target three gives two, not three ordered sequences.

    Use when: Enumeration is unnecessary and target-sized storage is affordable. Beyond normalization, work is additions and storage is . This is pseudo-polynomial in numeric target. Exact counts can require increasingly large integers.

Rebuild Eligibility

Does changing index to index + 1 merely optimize the original search?

Answer: No. It removes that occurrence from future eligibility, changing unlimited reuse to single-use positions.