FAANGPrep Sprint
Combination Sum
Find every combination that sums to a target, reusing numbers freely, and prune with a sorted break.
Examples
2 + 2 + 3 = 7 uses 2 twice, which is allowed; 7 on its own is the other.
Three combinations; no order within or between them matters.
The only candidate is already bigger than the target.
Problem Understanding
Given an array of distinct integers candidates and a target, return a list of all unique combinations where the chosen numbers sum to target.
Key Rule: The same number may be chosen from candidates an unlimited number of times.
Algorithm Strategy
Sort the candidates first. Then backtrack(start, remaining) tries each candidate from start onwards:
- Too big? If
candidates[i] > remaining, break — the list is sorted, so every candidate after it is too big as well. - Choose it: append it and subtract it from
remaining. - Explore with
backtrack(i, …)— the samei, because a number may be used again. - Unchoose: pop it before trying the next candidate.
When remaining reaches 0 the path is a combination: record it and return.
Passing i rather than 0 is what keeps each combination unique: a call never goes back to a smaller candidate, so [2, 2, 3] is built once and [3, 2, 2] never is.
Interactive Visualization
ONE NODE PER CALL · THE LABEL IS THE CANDIDATE ADDED, THE NUMBER BELOW IS WHAT IS LEFT · RED = REJECTED BY THE BREAK
SORT THE CANDIDATES
left to make
7
depth
0
Answer
—
path
[] — nothing chosen
candidates (sorted)
result
Nothing found yet
Sort the candidates — 2, 3, 6, 7 is already in order. Start with an empty path and 7 left to make
Next
Choose 2: the path is [2] and 5 is left
candidates
Target
Every node is one call to backtrack. Its label is the candidate that call added, and the number under it is what is still left to make — a node reading 0 is a combination.
A red node is the one candidate a call looked at and rejected with break: its number goes negative. The candidates after it are never looked at, so they are not drawn at all — that missing part of the tree is the saving. Try Unsorted to see why the sort has to come first.
