KatInterview

47. Permutations 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 for all unique permutations of a given array of numbers that may contain duplicates. This is a variation of the standard permutation problem. The main challenge is to devise a strategy to avoid generating duplicate permutations when the input array has identical elements.

Solution

Permutations II in Python

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        result = []
        path = []
        # Sort nums to handle duplicates
        nums.sort()
        used = [False] * len(nums)

        def backtrack():
            # Base case: a complete permutation is found
            if len(path) == len(nums):
                result.append(path[:]) # Append a copy of the path
                return

            for i in range(len(nums)):
                # Skip if element is already used
                if used[i]:
                    continue
                
                # Pruning logic for duplicates:
                # If current element is same as previous, and previous was not used,
                # it means we are about to generate a duplicate permutation.
                # By sorting and using this check, we ensure that for identical numbers,
                # we always pick them in their original sorted order.
                if i > 0 and nums[i] == nums[i-1] and not used[i-1]:
                    continue
                
                # Choose
                used[i] = True
                path.append(nums[i])
                
                # Explore
                backtrack()
                
                # Unchoose (backtrack)
                path.pop()
                used[i] = False

        backtrack()
        return result

Permutations II in Java

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        // Sort the array to handle duplicates
        Arrays.sort(nums);
        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 a full permutation is formed
        if (path.size() == nums.length) {
            result.add(new ArrayList<>(path)); // Add a copy of the path
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            // Skip if the element is already used
            if (used[i]) {
                continue;
            }
            // Pruning logic for duplicates:
            // If the current element is the same as the previous one,
            // and the previous one hasn't been used, skip the current one.
            // This ensures that for duplicate numbers, we pick them in a specific relative order.
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }

            // Choose
            used[i] = true;
            path.add(nums[i]);

            // Explore
            backtrack(nums, path, used, result);

            // Unchoose (backtrack)
            path.remove(path.size() - 1);
            used[i] = false;
        }
    }
}

Permutations II in C++

class Solution {
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int>> result;
        vector<int> path;
        vector<bool> used(nums.size(), false);
        // Sort the numbers to handle duplicates
        sort(nums.begin(), nums.end());
        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 is the same size as nums, we have a complete permutation
        if (path.size() == nums.size()) {
            result.push_back(path);
            return;
        }

        for (int i = 0; i < nums.size(); ++i) {
            // If the element is already used in the current path, skip it
            if (used[i]) {
                continue;
            }
            // Pruning step to avoid duplicate permutations
            // If the current element is the same as the previous one, and the previous one
            // has not been used, it means we are trying to create a duplicate permutation
            // by picking identical elements in a different order. To prevent this, we skip.
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }

            // Choose
            used[i] = true;
            path.push_back(nums[i]);

            // Explore
            backtrack(nums, path, used, result);

            // Unchoose (backtrack)
            path.pop_back();
            used[i] = false;
        }
    }
};

Permutations II in TypeScript

function permuteUnique(nums: number[]): number[][] {
    const result: number[][] = [];
    const path: number[] = [];
    const used: boolean[] = new Array(nums.length).fill(false);

    // Sort nums to handle duplicates effectively. Use a compare function for numbers.
    nums.sort((a, b) => a - b);

    function backtrack() {
        // Base case: if a complete permutation is formed
        if (path.length === nums.length) {
            result.push([...path]); // Add a copy of the current path
            return;
        }

        for (let i = 0; i < nums.length; i++) {
            // Skip elements that are already in the current path
            if (used[i]) {
                continue;
            }
            
            // Pruning condition to avoid duplicate permutations.
            // If the current number is the same as the previous one, and the previous one
            // has not been used, we skip it. This ensures that for a set of duplicate
            // numbers, we always pick them in a fixed relative order.
            if (i > 0 && nums[i] === nums[i - 1] && !used[i - 1]) {
                continue;
            }

            // Choose
            used[i] = true;
            path.push(nums[i]);
            
            // Explore
            backtrack();
            
            // Unchoose (backtrack)
            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.