Algorithms · Visualized

Combination Sum

Backtracking

Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.

Finds all unique combinations of numbers from a candidate set that add up to a target, where the same number can be reused multiple times. Time: O(n^(target/min)) average, O(2^target) in the loosest bound, depends heavily on candidate values worst; space: O(target / min candidate) recursion depth.

Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.

Combination Sum

Backtracking

Finds all unique combinations of numbers from a candidate set that add up to a target, where the same number can be reused multiple times. Backtracking tries adding each candidate, recursing with a reduced target, and backtracks when the target goes negative or hits zero.

How Combination Sum Works

  1. Sort the candidates (helps with early stopping and avoiding duplicate combinations).
  2. Start the recursion with an empty path and the full target.
  3. At each step, try each candidate from the current starting index onward (allowing the same index to be reused, since repeats are permitted).
  4. If adding a candidate makes the remaining target exactly 0, record the current path as a valid combination.
  5. If the remaining target goes negative, stop that branch (backtrack); otherwise recurse further with the reduced target, then backtrack (remove the candidate) to try the next option.

Combination Sum Worked Example

Input: {candidates: [2, 3, 6, 7], target: 7}

Try 2: remaining=5. Try 2 again: remaining=3. Try 2 again: remaining=1. Try 2 again: remaining=-1, backtrack. Try 3: remaining=0 at path [2,2,3] → record! Backtrack up, try 6 instead of second 2: path[2,6]... continue exploring. Try 7 alone: path[7], remaining=0 → record. Final combinations: [[2,2,3],[7]].

Combination SumO(2ⁿᵗ)
Find combinations that sum to a target, reusing candidates freely.
[] sum=0
results
Step 1 / 56
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Candidate 2 (sum 0): take it again, or skip to next
Python · Backtracking in Code
def combination_sum(cand, target):
    out = []
    def build(i, cur, rem):
        if rem == 0:
            out.append(cur[:])
            return
        for j in range(i, len(cand)):
            if cand[j] > rem:
                break
            cur.append(cand[j])
            build(j, cur, rem - cand[j])   # reuse same index
            cur.pop()
    cand.sort()
    build(0, [], target)
    return out

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Combination Sum Time & Space Complexity

BestExponential in the worst case
AverageO(n^(target/min))
WorstO(2^target) in the loosest bound, depends heavily on candidate values
SpaceO(target / min candidate) recursion depth

When to Use Combination Sum

  • Making change with unlimited coin supply, or any 'reach a target using repeatable building blocks' problem.
  • Recipe/formula generation where ingredients can be used multiple times to hit a target quantity.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.