KatInterview

46. Permutations

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 possible permutations of a given array of distinct integers. A permutation is a rearrangement of the elements of the array. For an array of length n, there are n! (n-factorial) possible permutations. Given the constraint nums.length <= 6, the maximum number of permutations is 6! = 720, which is a small number, suggesting that an algorithm with a time complexity related to n! is acceptable. A classic approach for this type of problem is backtracking.

Solution

Permutations in Python

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        result = []
        path = []
        # 'used' list to keep track of numbers used in the current permutation.
        used = [False] * len(nums)

        def backtrack():
            # Base case: if the path is complete, add a copy to the result.
            if len(path) == len(nums):
                result.append(path[:]) # Use path[:] to create a copy.
                return

            # Recursive step: iterate through all numbers.
            for i in range(len(nums)):
                # Skip numbers that are already used.
                if used[i]:
                    continue
                
                # Choose: add the number to the path and mark as used.
                path.append(nums[i])
                used[i] = True

                # Explore: recurse.
                backtrack()

                # Unchoose (backtrack): remove the number and unmark.
                path.pop()
                used[i] = False
        
        backtrack()
        return result

Permutations in Java

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        // 'used' array to keep track of numbers used in the current permutation.
        boolean[] used = new boolean[nums.length];
        backtrack(nums, new ArrayList<>(), used, result);
        return result;
    }

    private void backtrack(int[] nums, List<Integer> path, boolean[] used, List<List<Integer>> result) {
        // Base case: if the path has the same number of elements as nums,
        // we have found a complete permutation.
        if (path.size() == nums.length) {
            // Add a copy of the current path to the results.
            // new ArrayList<>(path) creates a shallow copy.
            result.add(new ArrayList<>(path));
            return;
        }

        // Recursive step: iterate through all numbers in nums.
        for (int i = 0; i < nums.length; i++) {
            // If the number at index i is already used, skip it.
            if (used[i]) {
                continue;
            }

            // Choose: add the number to the path and mark it as used.
            path.add(nums[i]);
            used[i] = true;

            // Explore: recursively call backtrack.
            backtrack(nums, path, used, result);

            // Unchoose (backtrack): remove the last element from the path and mark it as unused.
            path.remove(path.size() - 1);
            used[i] = false;
        }
    }
}

Permutations in C++

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> result;
        vector<int> path;
        // 'used' array to keep track of numbers used in the current permutation.
        vector<bool> used(nums.size(), false);
        backtrack(nums, path, used, result);
        return result;
    }

private:
    void backtrack(const vector<int>& nums, vector<int>& path, vector<bool>& used, vector<vector<int>>& result) {
        // Base case: if the path has the same number of elements as nums,
        // we have found a complete permutation.
        if (path.size() == nums.size()) {
            result.push_back(path); // Add a copy of the current path to the results.
            return;
        }

        // Recursive step: iterate through all numbers in nums.
        for (int i = 0; i < nums.size(); ++i) {
            // If the number is already used in the current path, skip it.
            if (used[i]) {
                continue;
            }

            // Choose: add the number to the path and mark it as used.
            path.push_back(nums[i]);
            used[i] = true;

            // Explore: recursively call backtrack to find permutations with the current path.
            backtrack(nums, path, used, result);

            // Unchoose (backtrack): remove the number from the path and mark it as unused
            // to explore other possibilities.
            path.pop_back();
            used[i] = false;
        }
    }
};

Permutations in TypeScript

function permute(nums: number[]): number[][] {
    const result: number[][] = [];
    const path: number[] = [];
    // 'used' array to keep track of numbers used in the current permutation.
    const used: boolean[] = new Array(nums.length).fill(false);

    function backtrack() {
        // Base case: if the path's length equals nums' length, a permutation is found.
        if (path.length === nums.length) {
            // Add a copy of the current path to the result.
            result.push([...path]); // Use spread syntax for a copy.
            return;
        }

        // Recursive step: iterate through all numbers.
        for (let i = 0; i < nums.length; i++) {
            // If the number at index i is already used, skip it.
            if (used[i]) {
                continue;
            }

            // Choose: add the number to the path and mark it as used.
            path.push(nums[i]);
            used[i] = true;

            // Explore: recursively call backtrack.
            backtrack();

            // Unchoose (backtrack): remove the number from path and mark as unused.
            path.pop();
            used[i] = false;
        }
    }

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