Limited Time Offer:Up to 20% off Hello Interview Premium
Up to 20% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Backtracking

Combination Sum

medium

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
DESCRIPTION (inspired by Leetcode.com)

Given an array of distinct integers candidates and a target integer target, generate all unique combinations of candidates which sum to target. The combinations may be returned in any order, and the same number may be chosen from candidates an unlimited number of times.

Constraints:

  • All values in candidates are positive integers.
  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All elements of candidates are distinct.
  • 1 <= target <= 40

Input:

candidates = [2,3,6,7]
target = 7

Output:

[[2,2,3],[7]]

Explanation:

2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations.

Solution

Visualization
Python
Language
Try these examples:
def combinationSum(candidates, target):
def backtrack(start, combo, current_target):
if current_target == 0:
result.append(list(combo))
return
for i in range(start, len(candidates)):
curr = candidates[i]
if candidates[i] > current_target:
return
combo.append(curr)
backtrack(i, combo, current_target - curr)
combo.pop()
return
candidates.sort()
result = []
backtrack(0, [], target)
return result
2367

combination sum

0 / 56

Explanation

This solution uses backtracking to find all the combinations of numbers that sum up to the target. The backtracking function is a recursive function that uses depth-first search to explore all possible combinations of candidates that sum up to the target. Each call to backtracking takes in parameters start, combo, and current_target. The start parameter is the index of the current candidate, combo is the current combination of numbers, and the current_target parameter is the target we are trying to hit (equal to target - the sum of combo).
The first step is to sort candidates, which makes it easy to tell when the current search combination exceeds the target, and can be pruned.
Visualization
Python
Language
def combinationSum(candidates, target):
def backtrack(start, combo, current_target):
if current_target == 0:
result.append(list(combo))
return
for i in range(start, len(candidates)):
curr = candidates[i]
if candidates[i] > current_target:
return
combo.append(curr)
backtrack(i, combo, current_target - curr)
combo.pop()
return
candidates.sort()
result = []
backtrack(0, [], target)
return result
2367

combination sum

0 / 1

Next, we kick off the search. Each call to the backtracking function first checks if the current_target is equal to 0. If so, that means the current value for combo is a valid solution, so we add it to the result. If not, the function iterates through the candidates starting from the start index. For each candidate, we add it to the current combination and recursively call the backtracking function with the updated current_target. Since we can use the same candidate multiple times, we pass the start index as the current index to the next call.
Visualization
Python
Language
def combinationSum(candidates, target):
def backtrack(start, combo, current_target):
if current_target == 0:
result.append(list(combo))
return
for i in range(start, len(candidates)):
curr = candidates[i]
if candidates[i] > current_target:
return
combo.append(curr)
backtrack(i, combo, current_target - curr)
combo.pop()
return
candidates.sort()
result = []
backtrack(0, [], target)
return result
2367result[]

sort candidates

0 / 10

Recursively exploring all combinations
If at any point the current_target becomes less than 0, we know that the current combo is not a valid solution, so we backtrack to the previous call.
For the backtracking step, we remove the last number from the current combination and try the next candidate. This process continues until we have tried all the candidates.
Visualization
Python
Language
def combinationSum(candidates, target):
def backtrack(start, combo, current_target):
if current_target == 0:
result.append(list(combo))
return
for i in range(start, len(candidates)):
curr = candidates[i]
if candidates[i] > current_target:
return
combo.append(curr)
backtrack(i, combo, current_target - curr)
combo.pop()
return
candidates.sort()
result = []
backtrack(0, [], target)
return result
def backtrack(start, combo, current_target):
if current_target == 0:
result.append(list(combo))
return
for i in range(start, len(candidates)):
curr = candidates[i]
if candidates[i] > current_target:
return
combo.append(curr)
backtrack(i, combo, current_target - curr)
combo.pop()
return
def backtrack(start, combo, current_target):
if current_target == 0:
result.append(list(combo))
return
for i in range(start, len(candidates)):
curr = candidates[i]
if candidates[i] > current_target:
return
combo.append(curr)
backtrack(i, combo, current_target - curr)
combo.pop()
return
def backtrack(start, combo, current_target):
if current_target == 0:
result.append(list(combo))
return
for i in range(start, len(candidates)):
curr = candidates[i]
if candidates[i] > current_target:
return
combo.append(curr)
backtrack(i, combo, current_target - curr)
combo.pop()
return
def backtrack(start, combo, current_target):
if current_target == 0:
result.append(list(combo))
return
for i in range(start, len(candidates)):
curr = candidates[i]
if candidates[i] > current_target:
return
combo.append(curr)
backtrack(i, combo, current_target - curr)
combo.pop()
return
2367i = 0result[]start0combo[2,2,2]current_target1

i = 0

0 / 2

Backtracking to the previous call. Notice how we `pop` from `combo` when we backtrack.

Complexity

Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(n^(T/m)) Let n be the number of candidates, T be the target value, and m be the smallest candidate. In the worst case, the recursion tree branches up to n ways at each level, and the maximum depth is T/m (achieved by repeatedly picking the smallest candidate). This gives an upper bound of O(n^(T/m)) nodes in the recursion tree. The sorting step takes O(n log n), which is dominated by the backtracking.

Space Complexity: O(T/m) The recursion goes at most T/m levels deep (each level subtracts at least m from the remaining target), so the call stack and the current combination together use O(T/m) space. We don't count the output list itself.

Mark as read

Next: Palindrome Partitioning

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Solution

Explanation

Complexity

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsAnthropic SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress