InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Backtracking

Subsets II

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug