Meta (Facebook) · Question 40 · Backtracking
Combination Sum
Problem
You are given array of candidates and target. Find all unique combinations that sum to target.
Approach
Sort, then backtrack with reuse, pruning when the remainder goes negative.
Time O(n^(t/m))Space O(t/m)
How it works
- 1Sort candidates to prune early.
- 2Reuse allowed: recurse from the same index.
- 3Copy the path when the remainder hits zero.
Sample input / output
Input: 3 8 2 3 5 Output: [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
Constraints
1 <= candidates.length <= 30; distinct; 1 <= target <= 500.
Solution — read it, then walk it
Time O(n^(t/m))Space O(t/m)Loops 1Branches 3Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/25
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits