Taro Logo

Combination Sum

#1 Most AskedMedium
265 views
Topics:
ArraysRecursion

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Example 1:

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.

Example 2:

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

Example 3:

Input: candidates = [2], target = 1
Output: []

Constraints:

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are the numbers in the candidates array guaranteed to be positive integers, or could we encounter zeros or negative numbers?
  2. Can the candidates array contain duplicate values, or are all the elements guaranteed to be distinct?
  3. What should be returned if no valid combination can sum up to the target?
  4. Is there any specific order required for the combinations in the output list, or can they be in any arbitrary order?
  5. Is there an upper bound on the maximum depth of the recursion tree or the maximum number of valid combinations we might generate?

Brute Force Solution

Approach

Imagine you have a collection of coin values and a specific target amount of money you want to make. The brute force approach is like exploring every single combination of coins possible to see which groups add up to your target amount.

Here's how the algorithm would work step-by-step:

  1. Start with an empty group of coins.
  2. Try adding any coin from your collection to your group.
  3. Check the total value of your current group of coins.
  4. If the total matches your target amount, save this group as a successful combination.
  5. If the total is less than your target amount, keep going by adding another coin to the group and checking again.
  6. If the total goes over your target amount, stop following that path because it is too large.
  7. Repeat this trial-and-error process for every possible combination of coins until you have tested every single way to reach the target.

Code Implementation

def combination_sum(candidates, target):
    successful_combinations = []

    def explore_combinations(current_index, current_group, current_total):
        # Stop exploring when the total exceeds our target amount
        if current_total > target:
            return

        # Save the group if the total matches our target amount exactly
        if current_total == target:
            successful_combinations.append(list(current_group))
            return

        # Try every candidate starting from the current index to allow reuse
        for index in range(current_index, len(candidates)):
            current_group.append(candidates[index])
            
            explore_combinations(index, current_group, current_total + candidates[index])
            current_group.pop()

    explore_combinations(0, [], 0)
    return successful_combinations

Big(O) Analysis

Time Complexity
O(2^(T/M)) – The time complexity is driven by a recursive backtracking search where each step branches based on the available candidate coins. In the worst case, the maximum depth of the recursion tree is determined by the target T divided by the minimum coin value M. Since we can reuse the same coin multiple times, each level of the recursion can branch up to n ways, leading to an exponential number of paths. The total operations approximate an exponential growth rate of 2 raised to the power of T/M, which simplifies to O(2^(T/M)).
Space Complexity
O(target / min_val) – The auxiliary space is primarily driven by the recursion stack frames and the temporary path list used to track the current group of coins. In the worst-case scenario where the smallest coin value is one, the maximum depth of the recursion tree reaches the target amount, denoted as N. Therefore, the memory consumed by the recursive calls and the current combination list grows linearly with respect to N before backtracking.

Optimal Solution

Approach

To find all ways to reach a specific target sum using a given set of numbers, the optimal approach uses a systematic building process. It explores different paths by repeatedly adding numbers, keeping track of the running total, and smartly backtracking whenever a path exceeds the target or successfully reaches it.

Here's how the algorithm would work step-by-step:

  1. Begin with an empty collection of chosen numbers and a starting total of zero.
  2. Look at the available numbers and choose one to add to your current collection.
  3. Check the new total after adding that number. If the total matches your goal, save this collection as a successful combination.
  4. If the total goes over your goal, stop following this path because adding more numbers will only make it larger.
  5. If the total is still under your goal, keep the same number in mind as an option for the future, allowing you to reuse it, and try adding another number.
  6. When a path finishes by either matching the target or going over, step backward to your previous choice and try the next available number.
  7. Repeat this trial-and-error process until every possible pathway has been explored, ensuring you find every unique combination without missing any options.

Code Implementation

class Solution:
    def combinationSum(self, candidate_numbers: list[int], target_goal: int) -> list[list[int]]:
        successful_combinations = []

        def depth_first_search(start_index: int, current_path: list[int], current_total: int):
            # Stop exploring this path early because exceeding the target sum cannot yield a solution.
            if current_total > target_goal:
                return

            if current_total == target_goal:
                successful_combinations.append(list(current_path))
                return

            for candidate_index in range(start_index, len(candidate_numbers)):
                chosen_number = candidate_numbers[candidate_index]
                current_path.append(chosen_number)

                # Allow reusing the same number by keeping the current candidate index in the recursive call.
                depth_first_search(candidate_index, current_path, current_total + chosen_number)
                current_path.pop()

        # Begin the search from the first index with an empty path and a zero starting total.
        depth_first_search(0, [], 0)
        return successful_combinations

Big(O) Analysis

Time Complexity
O(2^(T/M)) – The time complexity is driven by the recursive backtracking exploration, where T is the target sum and M is the minimum value in the candidate array. In the worst-case scenario, the algorithm can make branching decisions at each step up to a maximum depth of T divided by M. This generates an exponential search tree with a branching factor proportional to the number of available candidates. Consequently, the total number of operations approximates a geometric series bounded by O(2^(T/M)), which represents the maximum number of combinations explored.
Space Complexity
O(target / min) – The auxiliary space is primarily determined by the maximum depth of the recursion stack, which occurs when the algorithm repeatedly chooses the smallest available number, let's call its value min, to reach the target sum. This creates a recursion depth of up to target / min frames. Additionally, the temporary collection used to build paths stores at most target / min elements at any given time. Combining these factors yields a linear growth relative to the ratio of the target to the smallest candidate number. Therefore, simplifying to Big O notation, the space complexity is O(target / min).

Edge Cases

Empty candidates array or null input
How to Handle:
The recursion naturally terminates immediately and returns an empty list since no elements are available to process.
No valid combination can sum to the target
How to Handle:
The backtracking function will exhaust all valid paths without adding to the result list, ultimately returning an empty list.
Target is smaller than the smallest candidate
How to Handle:
The base case or loop condition checks if the remaining target becomes negative, immediately stopping further exploration of that branch.
Target is zero
How to Handle:
Depending on problem constraints, if the target is zero, the algorithm should return a single empty combination representing the base case.
Candidates array contains the number one
How to Handle:
This creates a deep recursion tree up to the depth of the target value, which may lead to a stack overflow or time limit exceeded error.
Single candidate matching the target exactly
How to Handle:
The algorithm adds the single-element combination to the result list and correctly terminates that branch of recursion.
Large target value leading to deep recursion
How to Handle:
Sorting the candidates array and pruning branches where the current candidate exceeds the remaining target prevents unnecessary deep recursion.
Duplicate combinations generated by the search space
How to Handle:
Passing the current index forward in recursive calls rather than resetting to zero ensures combinations are built in non-descending order to avoid duplicates.
0/57 completed