InterviewPrepKit

Home / Coding / Backtracking

Subsets II

medium Original β†—
Solving tips
  • Same as Subsets but with duplicate values: sort first so equal values are adjacent, then apply the same-level skip rule.
  • Skip candidates[i] when i > start and nums[i] == nums[i-1]: this blocks starting two sibling branches with the same value while still allowing consecutive picks like [2,2].
  • Use i > start, not i > 0, or you wrongly suppress legitimate repeats where a child extends its parent with an equal value.
  • Time is O(n * 2^n), O(n) extra space; recording at every node captures subsets of all sizes, and no set-based dedup is needed.

Problem

You are given an integer array nums that may contain duplicate values. Return every possible subset of nums (the power set), but the result must not contain two subsets that are equal as multisets β€” e.g. [1,2] and [2,1] count as the same subset, and [2] may only appear once even if 2 appears twice in the input.

Subsets may be returned in any order, and the elements inside each subset may be in any order.

Examples

  • nums = [1,2,2] β†’ [[], [1], [1,2], [1,2,2], [2], [2,2]] β€” the two 2s produce [2], [2,2], etc., but [2] is listed only once.
  • nums = [0] β†’ [[], [0]] β€” a single element gives the empty set and itself.
  • nums = [4,4,4] β†’ [[], [4], [4,4], [4,4,4]] β€” with all-equal elements, only subset sizes matter.

Constraints

  • 1 <= nums.length <= 10 β€” output can hold up to 2^10 = 1024 subsets, so exponential enumeration is expected and fine.
  • -10 <= nums[i] <= 10

Think about it first

Hint 1 If there were no duplicates, this would be plain Subsets: at each index, either include the element or skip it. What goes wrong when two equal values exist? Which two different choice sequences build the same subset?
Hint 2 Sort the array first so equal values sit next to each other. Now duplicate subsets can only arise from choosing "the second 2 but not the first 2" versus "the first 2 but not the second 2".
Hint 3 In the backtracking loop over candidate positions `i` from `start`, skip `nums[i]` whenever `i > start` and `nums[i] == nums[i-1]`: within one level of the tree, never start a new branch with a value you already branched on at that level. That single `continue` removes all duplicates with no set-based dedup needed.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.