LeetCode #90 Medium

Subsets II

Subsets II is LeetCode 90 (Medium). Given an array nums that may contain repeated values, return every subset, listing each distinct subset only once. Two subsets are the same when they hold the same values the same number of times, no matter which positions those values came from.

  • n is at most 10, so there are at most 1,024 subsets before repeats are removed.
  • The subsets may be returned in any order.
Constraints
  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
backtrackingrecursionbit manipulation
Open on LeetCode ↗
02

Intuition

Sort the array first, so equal values sit next to each other. Then build each subset by choosing which element comes next, always moving to the right.

At one level of the search, choosing the first 2 or the second 2 as the next element leads to exactly the same subsets, because everything after it can be chosen the same way. So each level tries every distinct value once: it skips an element equal to the one just before it in the same loop.

The skip only works inside one loop. A deeper call starts a fresh loop, so it may still take the second 2 after the first, and [2, 2] is still built.

How to spot this pattern

Listing unique subsets, combinations or permutations from an input with repeats always comes down to this: sort, then never start two sibling branches with the same value. The check is one line inside the usual backtracking loop.

03

Approach

Try it first

Before reading on, run the plain Subsets search on [2, 2] and list what it returns. Which two branches produce the same subset, and how could the loop tell them apart? Aim for O(n · 2^n) time.

1

Sort the array

Sorting puts equal values side by side, so a repeat can be spotted by comparing an element with its left neighbour. It costs O(n log n), which is tiny next to the output.

2

Save the current subset on every call

dfs(start) first appends a copy of path to res. Each call chooses which element comes next rather than deciding one element, so every call, including the first one with an empty path, stands for a different subset.

3

Try each later element as the next one

Loop i from start to the end: append nums[i], call dfs(i + 1), then pop it. The child starts at i + 1, so values are always added in sorted order and [1, 2] and [2, 1] cannot both appear.

4

Skip a value already tried in this loop

If i > start and nums[i] == nums[i - 1], continue to the next i. The equal element just before it was tried as the next pick a moment ago, and its branch already produced every subset this one would.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def subsetsWithDup(self, nums):
▶3 nums.sort()
▶4 res, path = [], []
▶5 
▶6 def dfs(start):
▶7 res.append(path[:])
▶8 for i in range(start, len(nums)):
▶9 if i > start and nums[i] == nums[i - 1]:
▶10 continue
▶11 path.append(nums[i])
▶12 dfs(i + 1)
▶13 path.pop()
▶14 
▶15 dfs(0)
▶16 return res
nums102122pathemptysavednonealready sorted: equal values side by side
nums[1, 2, 2]
Sorting puts equal values next to each other, so the loop can spot a repeat by comparing a number with the one just to its left.
nums102122start 0pathemptysaved∅save the empty subset
start0loop begins here
saved1
Every call stands for one subset, so the path [] is saved as soon as the call begins. Its loop then tries each number from index 0 on as the next one to add.
nums10i2122start 0path1saved∅add 1 → path 1
i0first in this loop
path[1]
Add 1 as the next number. The deeper call starts at index 1, so numbers are only ever added left to right.
nums102122start 1path1saved∅1save 1
start1loop begins here
saved2
Every call stands for one subset, so the path [1] is saved as soon as the call begins. Its loop then tries each number from index 1 on as the next one to add.
nums1021i22start 1path12saved∅1add 2 → path 1 2
i1first in this loop
path[1, 2]
Add 2 as the next number. The deeper call starts at index 2, so numbers are only ever added left to right.
nums102122start 2path12saved∅11 2save 1 2
start2loop begins here
saved3
Every call stands for one subset, so the path [1, 2] is saved as soon as the call begins. Its loop then tries each number from index 2 on as the next one to add.
nums102122istart 2path122saved∅11 2add 2 → path 1 2 2
i2first in this loop
path[1, 2, 2]
Add 2 as the next number. The deeper call starts at index 3, so numbers are only ever added left to right.
nums102122start 3: no numbers leftpath122saved∅11 21 2 2save 1 2 2
start3loop begins here
saved4
Every call stands for one subset, so the path [1, 2, 2] is saved as soon as the call begins. No numbers are left to add, so the call returns.
nums102122istart 2path12saved∅11 21 2 2back from that branch → remove 2
i2
path[1, 2]
Every subset that starts with [1, 2, 2] is saved. Remove 2 so the path is [1, 2] again and the loop can try the next index.
nums1021i22start 1path1saved∅11 21 2 2back from that branch → remove 2
i1
path[1]
Every subset that starts with [1, 2] is saved. Remove 2 so the path is [1] again and the loop can try the next index.
nums102122istart 1path1saved∅11 21 2 22 was just tried at this level → skip
i2i > start
nums[i]2same as nums[1]
The 2 at index 1 was already tried as the next number in this same loop, and its branch saved every subset this 2 would build. Starting again with 2 would only repeat them, so skip it.
nums10i2122start 0pathemptysaved∅11 21 2 2back from that branch → remove 1
i0
path[]
Every subset that starts with [1] is saved. Remove 1 so the path is [] again and the loop can try the next index.
nums1021i22start 0path2saved∅11 21 2 2add 2 → path 2
i1new value in this loop
path[2]
Add 2 as the next number; it differs from the number before it, so this branch is new. The deeper call starts at index 2, so numbers are only ever added left to right.
nums102122start 2path2saved∅11 21 2 22save 2
start2loop begins here
saved5
Every call stands for one subset, so the path [2] is saved as soon as the call begins. Its loop then tries each number from index 2 on as the next one to add.
nums102122istart 2path22saved∅11 21 2 22add 2 → path 2 2
i2first in this loop
path[2, 2]
Add 2 as the next number. The deeper call starts at index 3, so numbers are only ever added left to right.
nums102122start 3: no numbers leftpath22saved∅11 21 2 222 2save 2 2
start3loop begins here
saved6
Every call stands for one subset, so the path [2, 2] is saved as soon as the call begins. No numbers are left to add, so the call returns.
nums102122istart 2path2saved∅11 21 2 222 2back from that branch → remove 2
i2
path[2]
Every subset that starts with [2, 2] is saved. Remove 2 so the path is [2] again and the loop can try the next index.
nums1021i22start 0pathemptysaved∅11 21 2 222 2back from that branch → remove 2
i1
path[]
Every subset that starts with [2] is saved. Remove 2 so the path is [] again and the loop can try the next index.
nums102122istart 0pathemptysaved∅11 21 2 222 22 was just tried at this level → skip
i2i > start
nums[i]2same as nums[1]
The 2 at index 1 was already tried as the next number in this same loop, and its branch saved every subset this 2 would build. Starting again with 2 would only repeat them, so skip it.
nums102122pathemptysaved∅11 21 2 222 2all 6 distinct subsets → return them
len(res)6
result[[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
The search is over with 6 subsets and no repeats. Each skipped branch would have rebuilt subsets already saved, and every legal second copy of a value was still taken by a deeper loop.
05

Common pitfalls

Skipping with i > 0 instead of i > start

✗ Wrong
if i > 0 and nums[i] == nums[i - 1]:
    continue
✓ Right
if i > start and nums[i] == nums[i - 1]:
    continue

i > 0 also blocks the first pick of a deeper loop, which is a legal second copy. For [2, 2] the result is [[], [2]] and [2, 2] is lost. Only a repeat among siblings of the same loop should be skipped.

Forgetting to sort

✗ Wrong
res, path = [], []
dfs(0)
✓ Right
nums.sort()
res, path = [], []
dfs(0)

The skip compares neighbours, so it only works when equal values are adjacent. For [2, 1, 2] the unsorted run returns [2] twice, and both [2, 1] and [1, 2].

06

Edge cases

Every value is the same

[2, 2, 2] gives [[], [2], [2, 2], [2, 2, 2]]. Each loop takes its first 2 and skips the rest, so there is one subset per count of 2s.

07

Complexity

Time
O(n · 2^n)
Space
O(n)
The worst case is no repeats at all: 2^n subsets, each copied in up to n steps. Repeats only shrink the output, and skipped branches cost O(1) each. Sorting adds O(n log n). Apart from the output, the stack and path are at most n deep.
08

Subsets II FAQ

Why not generate all subsets with duplicates and put them in a set?

It works if you sort first and store tuples, but it builds every repeated subset just to throw it away. For ten 2s that is 1,024 lists for only 11 distinct answers. The skip rule never builds a repeat.

How many distinct subsets will there be?

Group equal values. A value that appears c times can be used 0 to c times, giving c + 1 choices, and the groups are independent. So the count is the product of (c + 1) over all groups. For [1, 2, 2] that is 2 × 3 = 6.

How is this different from Subsets?

In Subsets every value is different, so every branch gives a new subset and no check is needed. Here the loop form is used because the repeat check is one line inside it.