KatInterview

77. Combinations

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 possible combinations of k numbers from the range [1, n]. A key aspect of combinations is that the order of numbers does not matter. For instance, [1, 2] is the same combination as [2, 1]. This suggests a standard combinatorial search problem, which is a perfect fit for a backtracking algorithm.

Solution

Combinations in Python

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        result = []
        path = []

        def backtrack(start: int):
            # Base case: if the combination is complete
            if len(path) == k:
                # Add a copy of the path to the result
                result.append(path[:])
                return

            # Pruning: Calculate the end point for the loop.
            # We need k - len(path) more numbers.
            # The last possible starting number 'i' must satisfy n - i + 1 >= k - len(path),
            # which simplifies to i <= n - k + len(path) + 1.
            end = n - (k - len(path)) + 1
            
            # Explore numbers from 'start' up to the calculated end point
            for i in range(start, end + 1):
                # Choose the number i
                path.append(i)
                # Explore further, starting from the next number
                backtrack(i + 1)
                # Un-choose (backtrack)
                path.pop()
        
        backtrack(1)
        return result

Combinations in Java

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(1, n, k, new ArrayList<>(), result);
        return result;
    }

    private void backtrack(int start, int n, int k, List<Integer> path, List<List<Integer>> result) {
        // Base case: if the combination is of size k, add it to the result.
        if (path.size() == k) {
            // Add a copy of the current combination.
            result.add(new ArrayList<>(path));
            return;
        }

        // Iterate through possible numbers to add to the combination.
        // Pruning: The loop condition `i <= n - (k - path.size()) + 1` ensures
        // we have enough numbers left to form a combination of size k.
        for (int i = start; i <= n - (k - path.size()) + 1; i++) {
            // Choose the number i.
            path.add(i);
            // Explore further, starting from the next number.
            backtrack(i + 1, n, k, path, result);
            // Un-choose (backtrack) to explore other possibilities.
            path.remove(path.size() - 1);
        }
    }
}

Combinations in C++

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

private:
    void backtrack(int start, int n, int k, vector<int>& path, vector<vector<int>>& result) {
        // Base case: if the combination is of size k, add it to the result.
        if (path.size() == k) {
            result.push_back(path);
            return;
        }

        // Iterate through possible numbers to add to the combination.
        // Pruning: The loop condition ensures we don't explore branches that
        // cannot possibly form a combination of size k.
        // We need to pick (k - path.size()) more numbers.
        // The last possible starting number for a valid combination would be
        // n - (k - path.size()) + 1. Any number greater than that won't
        // leave enough remaining numbers to form a combination of size k.
        for (int i = start; i <= n - (k - path.size()) + 1; ++i) {
            // Choose the number i.
            path.push_back(i);
            // Explore further, starting from the next number.
            backtrack(i + 1, n, k, path, result);
            // Un-choose (backtrack) to explore other possibilities.
            path.pop_back();
        }
    }
};

Combinations in TypeScript

function combine(n: number, k: number): number[][] {
    const result: number[][] = [];
    const path: number[] = [];

    function backtrack(start: number) {
        // Base case: if the combination has reached size k
        if (path.length === k) {
            // Add a copy of the path to the results
            result.push([...path]);
            return;
        }

        // Iterate through possible numbers to add.
        // Pruning: The loop condition ensures we don't explore branches
        // that can't possibly form a valid combination.
        // We need k - path.length more numbers.
        // The last number we can start with is n - (k - path.length) + 1.
        for (let i = start; i <= n - (k - path.length) + 1; i++) {
            // Choose the number i
            path.push(i);
            // Explore with the next number
            backtrack(i + 1);
            // Un-choose (backtrack)
            path.pop();
        }
    }

    backtrack(1);
    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.