KatInterview

90. Subsets 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 subsets (the power set) from a given integer array that may contain duplicates. The main challenge is to generate all combinations without producing duplicate subsets. For instance, given [1, 2, 2], the subset [1, 2] should only appear once in the output, even though it can be formed by taking 1 and the first 2, or 1 and the second 2.

Solution

Subsets II in Python

class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        result = []
        path = []
        # Sort the array to handle duplicates efficiently.
        nums.sort()
        
        def backtrack(start: int):
            # Add a copy of the current subset to the result list.
            result.append(path[:])
            
            # Explore further options by adding more elements.
            for i in range(start, len(nums)):
                # Skip duplicates: if the current element is the same as the previous one,
                # and we are not at the start of the consideration for this level (i > start),
                # skip it to avoid generating duplicate subsets.
                if i > start and nums[i] == nums[i-1]:
                    continue
                
                # Choose: Add the current element to the path.
                path.append(nums[i])
                
                # Explore: Recurse with the next starting position.
                backtrack(i + 1)
                
                # Unchoose (backtrack): Remove the element to explore other possibilities.
                path.pop()
        
        backtrack(0)
        return result

Subsets II in Java

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        // Sort the array to handle duplicates efficiently.
        Arrays.sort(nums);
        backtrack(nums, 0, new ArrayList<>(), result);
        return result;
    }

    private void backtrack(int[] nums, int start, List<Integer> path, List<List<Integer>> result) {
        // Add a copy of the current subset to the result list.
        result.add(new ArrayList<>(path));

        // Explore further options by adding more elements.
        for (int i = start; i < nums.length; i++) {
            // Skip duplicates: if the current element is the same as the previous one,
            // and we are not at the start of the consideration for this level (i > start),
            // skip it to avoid generating duplicate subsets.
            if (i > start && nums[i] == nums[i-1]) {
                continue;
            }

            // Choose: Add the current element to the path.
            path.add(nums[i]);

            // Explore: Recurse with the next starting position.
            backtrack(nums, i + 1, path, result);

            // Unchoose (backtrack): Remove the element to explore other possibilities.
            path.remove(path.size() - 1);
        }
    }
}

Subsets II in C++

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        vector<vector<int>> result;
        vector<int> path;
        // Sort the array to handle duplicates efficiently.
        sort(nums.begin(), nums.end());
        backtrack(nums, 0, path, result);
        return result;
    }

private:
    void backtrack(const vector<int>& nums, int start, vector<int>& path, vector<vector<int>>& result) {
        // Add the current subset (a copy of path) to the result list.
        result.push_back(path);

        // Explore further options by adding more elements.
        for (int i = start; i < nums.size(); ++i) {
            // Skip duplicates: if the current element is the same as the previous one,
            // and we are not at the start of the consideration for this level (i > start),
            // skip it to avoid generating duplicate subsets.
            if (i > start && nums[i] == nums[i-1]) {
                continue;
            }
            
            // Choose: Add the current element to the path.
            path.push_back(nums[i]);
            
            // Explore: Recurse with the next starting position.
            backtrack(nums, i + 1, path, result);
            
            // Unchoose (backtrack): Remove the element to explore other possibilities.
            path.pop_back();
        }
    }
};

Subsets II in TypeScript

function subsetsWithDup(nums: number[]): number[][] {
    const result: number[][] = [];
    const path: number[] = [];
    // Sort the array to handle duplicates efficiently.
    nums.sort((a, b) => a - b);
    
    function backtrack(start: number) {
        // Add a copy of the current subset to the result list.
        result.push([...path]);

        // Explore further options by adding more elements.
        for (let i = start; i < nums.length; i++) {
            // Skip duplicates: if the current element is the same as the previous one,
            // and we are not at the start of the consideration for this level (i > start),
            // skip it to avoid generating duplicate subsets.
            if (i > start && nums[i] === nums[i - 1]) {
                continue;
            }

            // Choose: Add the current element to the path.
            path.push(nums[i]);
            
            // Explore: Recurse with the next starting position.
            backtrack(i + 1);
            
            // Unchoose (backtrack): Remove the element to explore other possibilities.
            path.pop();
        }
    }

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