0:00 / 0:00

List every subset of a list that has duplicates, with no repeats. Sort first, then skip a value already tried at the same depth.

▼

The problem

LeetCode 90 (Medium). Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The answer must not contain duplicate subsets; any order is fine.

Example (LeetCode's): [1, 2, 2] → [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]].

TRY IT ON LEETCODE ▶

The solution

def subsetsWithDup(nums):
    nums.sort()
    res, path = [], []
    def backtrack(start):
        res.append(path[:])
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue
            path.append(nums[i])
            backtrack(i + 1)
            path.pop()
    backtrack(0)
    return res

Transcript

Subsets Two. You get a list of numbers that may contain duplicates. Return every subset, but never the same one twice. It's Subsets, with twins.

Take one, two, two. There are six different subsets: empty, one, one two, one two two, two, and two two. Using the first two or the second gives the same subset, so it counts once.

The slow way builds all two to the n subsets, then drops the repeats with a set. For one, two, two, that's eight built for six kept. Two were copies, built in full just to be thrown away.

The fix: never build a copy. First, sort, so twins hang side by side, like socks on a line. Then grow each subset one sock at a time. At each depth, try every sock from start onward. But if a sock matches the one before it, and it isn't the first choice here, skip it. That value was already tried at this depth.

In code: sort the numbers. Backtrack records a copy of the path, then loops i from start. If i is past start, and nums of i equals nums of i minus one, continue. Otherwise, append it, recurse with i plus one, and pop it off.

Let's walk one, two, two. Record empty. Pick one, and record it. Pick two: one two. Pick the next two: one two two. Back at one's depth, the second two is a twin, so skip it. Back at the top, pick two, then two two. The last two is a twin at the top: skip. Six subsets, and not one repeat.

The worst case has no duplicates. Then there are two to the n subsets, each copied in up to n steps, so the time is order n times two to the n. The path and call stack are at most n deep, so the space is order n, plus the output.

Sort, skip the twins, recurse. That's Subsets Two.