Skip to content
Problem 90 · LeetCode 90(opens in a new tab)

Subsets II

MediumArrays

You get a list of whole numbers, nums, in which some values may repeat. Return every subset you can build from it: every way to keep some of the elements and leave out the rest, including keeping none and keeping all.

Two subsets that hold the same values the same number of times count as one, so list each only once. The subsets may come back in any order.

Example 1

Input:  nums = [3, 1, 3]
Output: [[], [1], [1, 3], [1, 3, 3], [3], [3, 3]]
Why:    picking either 3 alone gives the same [3]
2 more examples and the constraints

Example 2

Input:  nums = [5]
Output: [[], [5]]
Why:    keep the 5 or leave it out

Example 3

Input:  nums = [2, 2, 2]
Output: [[], [2], [2, 2], [2, 2, 2]]
Why:    only how many 2s you keep matters

Constraints

  • 1 ≤ length of nums ≤ 10
  • Every number is between −10 and 10

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every bitmask + a setO(n · 2ⁿ)
  2. Backtracking, skip repeatsO(n · 2ⁿ)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for ten equal numbersVerdict
Every bitmask + a setO(n · 2ⁿ)
Passes; builds repeats then drops them
Backtracking, skip repeatsO(n · 2ⁿ)
Best; never builds a repeat

n = how many numbers are in the list. With all values distinct both do the same work.

Edge cases to test

  • One number. [5] gives [[], [5]]: the empty subset always counts.
  • All values equal. [2, 2, 2] has only 4 subsets, one per count of 2s.
  • All values distinct. [1, 2, 3] has the full 8 subsets; the skip never fires.
  • Negative numbers. [-1, 0, -1] sorts to [-1, -1, 0]; sort by value, not as text.

Common mistakes

  • Forgetting to sort, so equal values are not next to each other and the skip misses them.
  • Skipping when i > 0 instead of i > start, which loses [3, 3].
  • Appending path itself instead of a copy, so every recorded subset ends up empty.

How to talk through it

  1. 1Clarify. Does the output order matter? Is the empty subset included? Can values be negative?
  2. 2Start without repeats. Without equal values this is plain subsets: 2ⁿ masks or a backtracking tree.
  3. 3Name the repeat. Equal values chosen at the same depth start the same branch. Sorting puts them side by side.
  4. 4Code the skip. Write the i > start and nums[i] == nums[i − 1] check and say why it is start, not 0.
  5. 5Test out loud. Run [3, 1, 3] and [2, 2, 2], and count the subsets you expect first.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?