← Whiteboard questions

Subsets II

List every distinct selection when numbers can repeat

DSA, Medium, Backtracking

Which structure or algorithm, and what does it cost.

A list nums may hold the same number more than once. Return every distinct subset of nums, including the empty one. Two subsets are the same if they hold the same numbers the same number of times. Write the numbers of each subset in increasing order. List the subsets in any order. Do not return the same subset twice.

Examples

Input nums = [2, 2, 5]
Output [[], [2], [2, 2], [2, 2, 5], [2, 5], [5]]
Why [2] appears once even though there are two 2s to pick from.
Input nums = [3]
Output [[], [3]]
Why one number gives the empty subset and [3].
Input nums = [7, 7, 7]
Output [[], [7], [7, 7], [7, 7, 7]]
Why only the count of 7s matters, so there are 4 subsets.

Constraints

Your answer must contain

Target Aim for O(n * 2^n) time in the worst case, and never build the same subset twice.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

If you treat equal numbers as different items, the same subset shows up more than once. Where do the extra copies come from?

Hint 2 the approach

Sort the list so equal numbers sit together. At one step of the loop, does it matter which of two equal numbers you start with?

Hint 3 the key step

In each loop over the next numbers, skip a number that equals the one before it, unless it is the first number of this loop. Otherwise add, recurse, remove.

Walkthrough

Full walkthrough brute force to best

Brute force

Sort the numbers once. Build all 2^n subsets by position and put each one, as a tuple, in a set to drop the repeats. This is correct and costs O(n * 2^n) time and memory. When numbers repeat, many of the 2^n subsets are repeats that are built and then thrown away.

Best method

Sort the numbers so equal ones sit together. Use the add, recurse, remove loop from plain subsets, with one extra rule. Inside one loop, if a number equals the one before it and is not the first number of this loop, skip it. The first copy already starts every subset that the second copy would start at this step. Copies can still be used together, because the call after the first copy starts at the second one. So [2, 2] is built, but [2] is not built twice. The work is at most that of plain subsets.

Hand trace

Run on [2, 2, 5], which is already sorted. Record []. Take the first 2 and record [2]. Take the second 2, which is allowed because it follows the first, and record [2, 2]. Take 5 and record [2, 2, 5]. Back at [2], take 5 and record [2, 5]. Back at the empty list, the second 2 equals the number before it in this loop, so skip it. Take 5 and record [5]. Six subsets.

Code

def unique_subsets(nums):
    nums = sorted(nums)
    out = []
    path = []
    def go(start):
        out.append(path[:])
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue
            path.append(nums[i])
            go(i + 1)
            path.pop()
    go(0)
    return out

Time and memory

O(n * 2^n) time in the worst case, when all numbers are different, and less when numbers repeat. Extra memory is O(n) for the list and the recursion, not counting the answer.

Common mistakes

  • Skipping a number whenever it equals the previous one. That also forbids [2, 2]. Skip only when the number is not the first of the loop.
  • Forgetting to sort. Equal numbers are then not neighbours, and the skip test misses them.
  • Building every subset and removing repeats at the end. It gives the right answer but does the extra work the skip rule avoids.

Related problems

More Backtracking problems
Subsets II: hints, walkthrough and Python solution