KatInterview

40. Combination Sum II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find all unique combinations from a given collection of candidate numbers (candidates) that sum up to a specific target. There are two key constraints:

Solution

Combination Sum II in Python

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        # Sort the candidates to handle duplicates efficiently.
        candidates.sort()
        
        result = []
        
        def backtrack(remaining_target, start_index, current_path):
            # Base case: If the remaining target is 0, we found a valid combination.
            if remaining_target == 0:
                result.append(list(current_path))
                return
            
            # Pruning: If remaining target becomes negative, this path is invalid.
            if remaining_target < 0:
                return

            # Explore candidates from the 'start_index'.
            for i in range(start_index, len(candidates)):
                # Key step for avoiding duplicate combinations:
                # If the current element is the same as the previous one, and it's not the first
                # element we are considering at this level of recursion, skip it.
                if i > start_index and candidates[i] == candidates[i-1]:
                    continue
                
                # Pruning optimization: if current candidate is greater than remaining target,
                # no point in checking further as the array is sorted.
                if candidates[i] > remaining_target:
                    break

                # Choose: Add the candidate to the current path.
                current_path.append(candidates[i])
                
                # Explore: Recurse with the next index (i + 1), as each number can be used once.
                backtrack(remaining_target - candidates[i], i + 1, current_path)
                
                # Backtrack: Remove the candidate to explore other possibilities.
                current_path.pop()

        backtrack(target, 0, [])
        return result

Combination Sum II in Java

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        // Sort candidates to handle duplicates and for early pruning.
        Arrays.sort(candidates);
        backtrack(candidates, target, 0, new ArrayList<>(), result);
        return result;
    }

    private void backtrack(int[] candidates, int remainingTarget, int start, List<Integer> currentCombination, List<List<Integer>> result) {
        // Base case: If the target is met, we found a valid combination.
        if (remainingTarget == 0) {
            result.add(new ArrayList<>(currentCombination));
            return;
        }

        // Base case: If target becomes negative, this path is invalid.
        if (remainingTarget < 0) {
            return;
        }

        // Iterate through candidates starting from the 'start' index.
        for (int i = start; i < candidates.length; i++) {
            // Key step to avoid duplicate combinations:
            // If the current element is the same as the previous one, and we are not at the
            // first element of this recursive call's loop (i > start), we skip it.
            // This ensures that for a set of duplicates, we only start a new path with the first one.
            if (i > start && candidates[i] == candidates[i - 1]) {
                continue;
            }
            
            // Pruning: if the current candidate is larger than the remaining target,
            // all subsequent candidates will also be larger, so we can stop.
            if (candidates[i] > remainingTarget) {
                break;
            }

            // Choose: Add the current candidate to the combination.
            currentCombination.add(candidates[i]);

            // Explore: Recurse with the next index (i + 1) as each number can be used only once.
            backtrack(candidates, remainingTarget - candidates[i], i + 1, currentCombination, result);

            // Backtrack: Remove the last added candidate to explore other paths.
            currentCombination.remove(currentCombination.size() - 1);
        }
    }
}

Combination Sum II in C++

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        // Sort the candidates to handle duplicates efficiently.
        sort(candidates.begin(), candidates.end());
        
        vector<vector<int>> result;
        vector<int> currentCombination;
        
        backtrack(candidates, target, 0, currentCombination, result);
        
        return result;
    }

private:
    void backtrack(const vector<int>& candidates, int remainingTarget, int start, 
                   vector<int>& currentCombination, vector<vector<int>>& result) {
        // Base case: If the remaining target is 0, we found a valid combination.
        if (remainingTarget == 0) {
            result.push_back(currentCombination);
            return;
        }
        
        // Base case: If remaining target is negative, this path is not valid.
        if (remainingTarget < 0) {
            return;
        }

        // Explore candidates from the 'start' index.
        for (int i = start; i < candidates.size(); ++i) {
            // Skip duplicates: If the current element is the same as the previous one,
            // and we are not at the beginning of the current exploration level (i > start),
            // skip it to avoid duplicate combinations.
            if (i > start && candidates[i] == candidates[i-1]) {
                continue;
            }

            // Pruning: if the current candidate is larger than the remaining target,
            // any subsequent candidate will also be larger (since the array is sorted),
            // so we can stop exploring this path.
            if (candidates[i] > remainingTarget) {
                break;
            }
            
            // Choose the current candidate.
            currentCombination.push_back(candidates[i]);
            
            // Explore the next level of recursion.
            // We pass i + 1 because each number can be used only once.
            backtrack(candidates, remainingTarget - candidates[i], i + 1, currentCombination, result);
            
            // Backtrack: Remove the current candidate to explore other possibilities.
            currentCombination.pop_back();
        }
    }
};

Combination Sum II in TypeScript

function combinationSum2(candidates: number[], target: number): number[][] {
    const result: number[][] = [];
    // Sort candidates to handle duplicates and enable pruning.
    candidates.sort((a, b) => a - b);

    function backtrack(remainingTarget: number, start: number, currentPath: number[]) {
        // Base case: A valid combination is found.
        if (remainingTarget === 0) {
            // Add a copy of the current path to the result.
            result.push([...currentPath]);
            return;
        }

        // Pruning: If remaining target is negative, stop this path.
        if (remainingTarget < 0) {
            return;
        }

        // Iterate through candidates from the 'start' index.
        for (let i = start; i < candidates.length; i++) {
            // Key step to avoid duplicate combinations:
            // If the current element is the same as the previous one and we are not at the 
            // beginning of this level's choices (i > start), skip it.
            if (i > start && candidates[i] === candidates[i - 1]) {
                continue;
            }

            // Pruning optimization: if current candidate is > remaining target,
            // subsequent ones will also be, so we can break the loop.
            if (candidates[i] > remainingTarget) {
                break;
            }

            // Choose the current candidate.
            currentPath.push(candidates[i]);

            // Explore: Recurse with the next index (i + 1) since each number can be used only once.
            backtrack(remainingTarget - candidates[i], i + 1, currentPath);

            // Backtrack: Remove the candidate to explore other paths.
            currentPath.pop();
        }
    }

    backtrack(target, 0, []);
    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.