← Google bank

Google · Question 75 · Backtracking

Combination Sum

BacktrackingPythoncode⏱ O(2^t)💾 O(t)
Product-based

Problem

Find all unique combinations where candidate numbers sum to target. Candidates can be used unlimited times.

Approach

Use backtracking to explore combinations.

Time O(2^t)Space O(t)

How it works

  1. 1Sort candidates to enable pruning.
  2. 2Backtrack: add a candidate to the path while the target allows.
  3. 3Append a copy of the path when the target reaches zero.
  4. 4Explore the next candidates from the current index.

Sample input / output

Input:
4 7
2 3 6 7
Output:
[[2, 2, 3], [7]]

Constraints

1 <= candidates.length <= 30; 1 <= candidates[i] <= 200; all unique; 1 <= target <= 500.

Solution — read it, then walk it

Time O(2^t)Space O(t)Loops 1Branches 3Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesno↻ repeatyesnoSTARTcandidates, targetres = []candidates.sort()DEFINE backtrack(start,path, target)if target == 0res.append(path[:])RETURNif target < 0RETURNfor i in range(start,len(candidates))path.append(candidates[i])backtrack(i, path, target -candidates[i])path.pop()backtrack(0, [], target)RETURN resDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it)); target =int(next(it))candidates = [int(next(it))for _ in range(n)]print(combinationSum(candidates,target))if __name__ =="__main__"main()END
  • 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