Skip to content

Interview Solver

FeaturesPricingHelp
Sign In
FeaturesPricingHelpSign In
  1. Interview Questions
  2. /
  3. Problems
  4. /
  5. Combination Sum

Combination Sum

List every multiset of numbers from a set of candidates that adds up to a target, reusing numbers as often as you like. The standard template for backtracking without duplicate results. Solve it below in Python or JavaScript, then read the walkthrough.

Solve it in your browserRead the solution
MediumArrayBacktrackingAsked at 111 companies incl. Google, Amazon, Meta

Problem

You're given an array of distinct positive integers candidates and a positive integer target. Return every unique combination of candidates whose sum is exactly target.

You may use the same candidate any number of times. Two combinations are the same if they use each number the same number of times, so [2, 3, 3] and [3, 2, 3] count once.

Return the combinations in any order, and the numbers inside each combination in any order. If no combination works, return an empty list.

Example 1

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

Example 2

Input
candidates = [8, 7, 4, 3], target = 11
Output
[[3, 4, 4], [3, 8], [4, 7]]

4 is used twice in the first combination.

Example 3

Input
candidates = [4], target = 2
Output
[]

The only candidate is already larger than the target.

Constraints

  • 1 ≤ candidates.length ≤ 30
  • 2 ≤ candidates[i] ≤ 40, and all candidates are distinct.
  • 1 ≤ target ≤ 40
  • The number of valid combinations is under 150.

Practice

1
2
3
4

Runs 11 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.

Get asked Combination Sum in a real interview?

Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.

Start Free Trial

How to solve Combination Sum

Pattern: Backtracking with a start index

Building combinations one number at a time is a tree search: at each step pick a candidate, subtract it from the remaining target, and recurse. The question is how to avoid producing [2, 3, 3] and [3, 2, 3] as separate answers.

The fix is to only ever pick candidates in non-decreasing index order. Pass a start index into the recursion: you may choose candidates[start] again (reuse is allowed) or anything after it, but never anything before. Every multiset then has exactly one path to it.

Sorting the candidates first gives a free prune: once a candidate is bigger than what remains, every later one is too, so you can stop the loop.

Approach 1: Generate ordered sequences, then de-duplicate

Recurse over every candidate at every step, and when the sum hits the target, sort the path and add it to a set. Correct, but explores every permutation of each answer, which grows factorially with combination length.

Time Exponential, with many repeated paths · Space O(target) recursion plus the set

Approach 2: Backtracking with a start index and pruning

  1. Sort candidates.
  2. dfs(start, remaining, path): if remaining == 0, record a copy of path.
  3. Loop i from start. If candidates[i] > remaining, break. Otherwise push it, call dfs(i, remaining - candidates[i], path) (same i, so it can repeat), and pop.

Each answer is produced exactly once and dead branches are cut immediately.

Time O(k · N) where N is the number of tree nodes, bounded by roughly n^(target/min) · Space O(target / min) recursion depth

ApproachTimeSpace
Generate ordered sequences, then de-duplicateExponential, with many repeated pathsO(target) recursion plus the set
Backtracking with a start index and pruningO(k · N) where N is the number of tree nodes, bounded by roughly n^(target/min)O(target / min) recursion depth

Solution code

Try the practice editor first. Both solutions pass every test above.

▸Combination Sum solution in Python
def combination_sum(candidates: list[int], target: int) -> list[list[int]]:
    candidates = sorted(candidates)
    results = []
    path = []

    def dfs(start, remaining):
        if remaining == 0:
            results.append(path[:])
            return
        for i in range(start, len(candidates)):
            c = candidates[i]
            if c > remaining:
                break
            path.append(c)
            dfs(i, remaining - c)  # i, not i + 1: reuse is allowed
            path.pop()

    dfs(0, target)
    return results
▸Combination Sum solution in JavaScript
function combinationSum(candidates, target) {
  const sorted = [...candidates].sort((a, b) => a - b);
  const results = [];
  const path = [];

  const dfs = (start, remaining) => {
    if (remaining === 0) {
      results.push([...path]);
      return;
    }
    for (let i = start; i < sorted.length; i++) {
      const c = sorted[i];
      if (c > remaining) break;
      path.push(c);
      dfs(i, remaining - c); // i, not i + 1: reuse is allowed
      path.pop();
    }
  };

  dfs(0, target);
  return results;
}

Common mistakes

  • Restarting the loop at 0 on every call, which produces the same combination in several orders.
  • Recursing with `i + 1` instead of `i`, which forbids reusing a candidate.
  • Appending `path` itself instead of a copy, so every stored result ends up as the same emptied list.
  • Breaking on `candidates[i] > remaining` without sorting first, which skips valid smaller candidates later in the list.

What interviewers look for

Draw the first two levels of the decision tree and point out where duplicates would come from. Then introduce the start index as the rule that removes them. Interviewers want to hear "each combination is generated in sorted order, so exactly once."

Mention the sort-and-break prune and the "push, recurse, pop" structure out loud, since this template is reused in Combination Sum II, Subsets and Permutations.

Follow-up questions

What if each candidate could be used at most once and the list could contain duplicates?

Sort, recurse with `i + 1`, and skip `candidates[i]` when `i > start` and it equals `candidates[i - 1]`. That removes duplicate branches at the same tree level while still allowing equal values deeper in one path.

What if you only needed the number of combinations?

That is the coin change ways problem: `dp[0] = 1`, and for each candidate c, for s from c to target, `dp[s] += dp[s - c]`. Looping over candidates on the outside counts multisets, not orderings. It runs in O(n · target).

What if you needed the combination with the fewest numbers?

Use a min-coins DP (`best[s] = 1 + min(best[s - c])`) or a BFS over remaining sums. Both are O(n · target) and avoid enumerating every combination.

Companies that ask Combination Sum

Combination Sum is tagged by 111 companies in our interview dataset. The score shows how often it comes up at each company.

  • Globant100%
  • Innovaccer100%
  • Think Surgical100%
  • Hpe100%
  • Juniper Networks100%
  • Ericsson92%
  • Weedmaps92%
  • Commscope91%
  • Bayer89%
  • Wp Engine89%
  • Motional86%
  • Reify Health84%
  • Synology83%
  • Snap82.5%
  • Unacademy81%
  • Bae Systems80%
  • Calix80%
  • Improbable80%
  • Floqast79%
  • Traveloka75%
  • Bolt Eu74%
  • Hashicorp73%
  • Renesas Electronics73%
  • Confluent72.8%

and 87 more.

Practice next

  • Word SearchMediumGrid backtracking (DFS)
  • Subsets IIMediumBacktracking with duplicate skipping
  • Word Break IIHardBacktracking with memoization
  • Two SumEasyHash map of complements

Get live help in the real interview

Working solutions in real time during your actual interview. Invisible to screensharing.

Start Free Trial

No credit card required

Interview Solver
  • Home
  • About
  • Pricing
  • Sign in
  • Contact
  • Blog
  • Companion
  • Mobile
  • Help Center
  • Developers
  • Use Cases
  • AI Interview Copilot
  • Coding Interview Copilot
  • AI Interview Assistant
  • Software Engineer
  • Product Manager
  • Misc
  • Privacy Policy
  • Terms and Conditions
  • Refund & Cancellation
  • Discord Community
  • Affiliate Program
  • Compare
  • All Comparisons
  • vs Final Round AI
  • vs UltraCode
  • vs Interview Coder
  • vs LockedIn AI
  • vs AI Apply
  • Free Tools
  • ATS Resume Checker
  • STAR Method Builder
  • Salary Lookup
  • Big O Cheat Sheet
  • Total Comp Calculator
  • View All →
  • Interview Questions
  • Google Questions
  • Amazon Questions
  • Microsoft Questions
  • Meta Questions
  • Apple Questions
  • TikTok Questions
  • View All →
© 2026 Interview Solver, Inc. All rights reserved.