← L&T Mindtree bank

L&T Mindtree · Question 40 · Backtracking

Combination Sum

BacktrackingJavacode⏱ O(2^t)💾 O(t/m)
Service-based

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(2^t)Space O(t/m)

How it works

  1. 1Sort candidates to prune early.
  2. 2Reuse allowed: recurse from the same index.

Sample input / output

Input:
candidates = [2, 3, 5], target = 8
Output:
[[2, 2, 2, 2], [2, 3, 3], [3, 5]]

Constraints

Distinct candidates; 1 <= target <= 500.

Solution — read it, then walk it

Time O(2^t)Space O(t/m)Loops 1Branches 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>> result= new ArrayList<>()Arrays.sort(candidates)backtrack(candidates,target, 0, newArrayList<>(), result)RETURN resultDEFINE static voidbacktrack(int[] candidates,int remain, int start,List<Integer> current,List<List<Integer>> result)if (remain == 0)result.add(newArrayList<>(current))RETURNif (remain < 0) returnfor (int i = start; i< candidates.length;i++)current.add(candidates[i])backtrack(candidates,remain - candidates[i], i,current, result)current.remove(current.size()- 1)DEFINE static voidmain(String[] args)System.out.println(combinationSum(newint[]{2, 3, 5}, 8))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/20

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