KatInterview

216. Combination Sum III

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 for all unique combinations of k distinct numbers from the set {1, 2, ..., 9} that sum up to a target value n. This is a classic combinatorial problem that is well-suited for a backtracking approach.

Solution

Combination Sum III in Python

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        results = []

        def backtrack(remain_k: int, remain_n: int, start: int, path: List[int]):
            # Base case: if we have found k numbers and their sum is n
            if remain_k == 0 and remain_n == 0:
                # A valid combination is found, add a copy to results
                results.append(list(path))
                return

            # Pruning: if we need more numbers but the sum is already too small,
            # or we have k numbers but the sum is not n.
            if remain_k == 0 or remain_n < 0:
                return

            # Explore numbers from 'start' to 9
            for i in range(start, 10):
                # Pruning: if remaining sum is less than the current number,
                # any subsequent number will also be too large.
                if remain_n < i:
                    break
                
                # Choose the number i
                path.append(i)

                # Explore the next number
                # We need one less number, remaining sum is reduced by i, and next start is i+1
                backtrack(remain_k - 1, remain_n - i, i + 1, path)

                # Unchoose (backtrack)
                path.pop()

        # Initial call to start the backtracking process
        backtrack(k, n, 1, [])
        return results

Combination Sum III in Java

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        // Start the backtracking process
        backtrack(k, n, 1, new ArrayList<>(), result);
        return result;
    }

    private void backtrack(int k, int n, int start, List<Integer> path, List<List<Integer>> result) {
        // Base case: if we have found k numbers and their sum is n
        if (k == 0 && n == 0) {
            result.add(new ArrayList<>(path)); // Add a copy of the valid combination
            return;
        }

        // Pruning: if we need to find more numbers but the remaining sum is negative, or k is 0 but n is not.
        if (k == 0 || n < 0) {
            return;
        }

        // Explore numbers from 'start' to 9
        for (int i = start; i <= 9; i++) {
            // Pruning: if the remaining sum 'n' is less than the current number 'i',
            // any subsequent number will also be too large, so we can stop.
            if (n < i) {
                break;
            }

            // Choose the number i
            path.add(i);

            // Explore the next number
            // We need k-1 more numbers, the remaining sum is n-i, and the next number must be at least i+1
            backtrack(k - 1, n - i, i + 1, path, result);

            // Unchoose (backtrack)
            path.remove(path.size() - 1);
        }
    }
}

Combination Sum III in C++

class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> result;
        vector<int> path;
        backtrack(k, n, 1, path, result);
        return result;
    }

private:
    void backtrack(int k, int n, int start, vector<int>& path, vector<vector<int>>& result) {
        // Base case: if we have found k numbers and their sum is n
        if (k == 0 && n == 0) {
            result.push_back(path);
            return;
        }

        // Pruning: if we need to find more numbers but the remaining sum is negative, or k is 0 but n is not.
        if (k == 0 || n < 0) {
            return;
        }

        // Explore numbers from 'start' to 9
        for (int i = start; i <= 9; ++i) {
            // Pruning: if the remaining sum 'n' is less than the current number 'i',
            // any subsequent number will also be too large, so we can stop.
            if (n < i) {
                break;
            }

            // Choose the number i
            path.push_back(i);

            // Explore the next number
            // We need k-1 more numbers, the remaining sum is n-i, and the next number must be at least i+1
            backtrack(k - 1, n - i, i + 1, path, result);

            // Unchoose (backtrack)
            path.pop_back();
        }
    }
};

Combination Sum III in TypeScript

function combinationSum3(k: number, n: number): number[][] {
    const results: number[][] = [];

    function backtrack(remain_k: number, remain_n: number, start: number, path: number[]) {
        // Base case: if we have found k numbers and their sum is n
        if (remain_k === 0 && remain_n === 0) {
            results.push([...path]); // Add a copy of the valid combination
            return;
        }

        // Pruning: if we need more numbers but the sum is already too small,
        // or we have k numbers but the sum is not n.
        if (remain_k === 0 || remain_n < 0) {
            return;
        }

        // Explore numbers from 'start' to 9
        for (let i = start; i <= 9; i++) {
            // Pruning: if remaining sum is less than the current number,
            // any subsequent number will also be too large.
            if (remain_n < i) {
                break;
            }
            
            // Choose the number i
            path.push(i);

            // Explore the next number
            // We need one less number, remaining sum is reduced by i, and next start is i+1
            backtrack(remain_k - 1, remain_n - i, i + 1, path);

            // Unchoose (backtrack)
            path.pop();
        }
    }

    // Initial call to start the backtracking process
    backtrack(k, n, 1, []);
    return results;
};

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.