Combine same-index reuse with a nondecreasing choice boundary and positive remaining-target decrease, then switch to finite occurrences or count-only DP.
QuestionInterview executionCoding practice
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.
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
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?
Sources and provenance
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:
Path
start
remaining
Next action
[]
0
7
Choose 2
[2]
0
5
Reuse 2
[2,2]
0
3
Try 2, then 3
[2,2,2]
0
1
Break because 2 is too large
[2,2,3]
1
0
Copy a solution
[7]
3
0
Copy the other solution
Keep sum(path) + remaining == target. start is the lowest eligible choice index, not the path length.
Passing the sameindex 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.
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
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.
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 O(target) call-stack space when the
smallest choice is 1.
For N inputs and U positive unique values, normalization costs expected O(N+Ulog(U+1)).
With positive target, depth is at most ⌊target/min(choices)⌋ 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.
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.
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.
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 O(U⋅target) additions and storage is O(target+U).
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.