← Microsoft bank

Microsoft · Question 75 · Backtracking

Combination Sum

BacktrackingJavacode⏱ O(2^t)💾 O(target)
Product-based

Problem

Given an array of distinct integers and a target, return all combinations where elements sum to the target. You may reuse elements.

Approach

Sort and backtrack from the current index (reuse allowed).

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

How it works

  1. 1Sort candidates to prune early.
  2. 2Reuse allowed: recurse from the same index.
  3. 3Copy the path when the remainder hits zero.

Sample input / output

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

Constraints

1 <= candidates.length <= 30; distinct; 1 <= target <= 500.

Solution — read it, then walk it

Time O(2^t)Space O(target)Loops 2Branches 2Returns 2source · Java
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE staticList<List<Integer>>combinationSum(int[…List<List<Integer>> res =new ArrayList<>()Arrays.sort(candidates)backtrack(res, newArrayList<>(), candidates,target, 0)RETURN resDEFINE static voidbacktrack(List<List<Integer>>res, List<Integer> temp…DEFINE remain, int start)if (remain == 0)res.add(newArrayList<>(temp))RETURNif (remain < 0) returnfor (int i = start; i< nums.length; i++)temp.add(nums[i])backtrack(res, temp, nums,remain - nums[i], i); //not i + 1 because we ca…temp.remove(temp.size() -1)DEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE n = sc.nextInt();int target = sc.nextInt()DEFINE [] candidates = newint[n]for (int i = 0; i <candidates.length;i++) candidates[i] …System.out.println(combinationSum(candidates,target))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/24

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