Subsets II

35 min · subsetsWithDup()

Two identical coupon values shouldn't create two identical coupon bundles. Repeated input values add choices, but they must not duplicate answers.

nums may repeat a value. Build every unique subset — a selection of zero or more input positions. A value may appear in a subset only as many times as it appears in nums.

Keep these output rules firm:

  • Write every subset in ascending numeric order.
  • Include the empty subset [].
  • Return no duplicate subsets, even when different positions lead to the same values.
  • The outer list may appear in any order.

Constraints

  • 1 <= nums.length <= 12
  • -100 <= nums[i] <= 100
  • Duplicate values are allowed.

Hints

A correct baseline

A bitmask can select positions, but two masks may now produce the same values. Sort each result and store it by an exact tuple key to remove duplicates.

Put equal values together

Sort a copy of nums before searching. Equal choices then sit next to each other, which makes a local skip rule possible.

Skip only at the same depth

Inside one recursive loop, ignore a value equal to the previous candidate. Don't ban it at deeper levels — choosing the second 2 after the first is how [2, 2] remains possible.

Follow-up

If a value appears k times, a subset can use it zero through k times. Can you use that copy count to predict the number of unique subsets before generating them?

Visible cases

Examples

Example 1

ready
Input
nums = [
  1,
  2,
  2
]
Expected
[
  [],
  [
    1
  ],
  [
    2
  ],
  [
    1,
    2
  ],
  [
    2,
    2
  ],
  [
    1,
    2,
    2
  ]
]
Why
the two positions holding 2 don't duplicate [2] or [1, 2]

Example 2

ready
Input
nums = [
  0,
  0
]
Expected
[
  [],
  [
    0
  ],
  [
    0,
    0
  ]
]
Why
zero may be chosen zero, one, or two times

Example 3

ready
Input
nums = [
  -1,
  2,
  -1
]
Expected
[
  [],
  [
    -1
  ],
  [
    -1,
    -1
  ],
  [
    2
  ],
  [
    -1,
    2
  ],
  [
    -1,
    -1,
    2
  ]
]
Why
repeated negatives follow the same copy-count rule

Interview signal

Asked at

AmazonMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite