Subsets II

medium

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution set must not contain any duplicate subset, and you may return the subsets in any order.

A subset is any selection of the elements — including the empty selection and the whole array — where each element is used at most as many times as it appears in nums.

Hints

The plain power set of n items has 2^n subsets — but duplicate values in nums make some of those subsets identical. How do you keep only one copy of each?
Sort nums first. Now every duplicate value sits right next to its twin, so a repeat is always the element just before.
During backtracking, at each level skip a value equal to the previous one you already tried here: if i > start and nums[i] == nums[i-1]: continue.

Common doubts

Sorting places equal values next to each other. Then a duplicate of nums[i] is always nums[i-1], so detecting a repeated choice becomes a single neighbor comparison instead of a set lookup.
i > start means the duplicate is a sibling choice at the current level — one already tried here. Using i > 0 would also block taking a duplicate deeper in the path (after its twin was already taken), which is exactly how a subset like [2,2] gets built.
No. In subset backtracking the current path is a valid subset at every node, so record it on entry to each call — the empty subset comes from the very first call.

Interview follow-ups

Drop the sort and the duplicate-skip guard — the same backtracking that records path at every node already yields all 2^n unique subsets.
Same sort-and-skip-duplicate skeleton; add a running sum, prune a branch once it exceeds the target, and record a path only when the sum hits the target.
Sort, then use a used array and skip nums[i] when i > 0 && nums[i] == nums[i-1] && !used[i-1] — the permutation analogue of the same sibling-duplicate rule.

Fun facts

  • The 'sort, then skip the equal sibling' guard is a template: Subsets II, Combination Sum II, and Permutations II are the same three lines with a different base case.
  • An array of n distinct items has exactly 2^n subsets — one per binary number of n bits, which is precisely why the bitmask enumeration works so cleanly.

Asked at

AmazonFacebookMicrosoftGoogleBloomberg
Frequently Sometimes Occasionally
Example 1
Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
Even though there are two 2's to choose from, the subset [1,2] is listed only once.
Example 2
Input: nums = [0]
Output: [[],[0]]
Constraints

- 1 <= nums.length <= 10 - -10 <= nums[i] <= 10

Solve this problem →