Subsets II (With Duplicates)

MediumBacktrackingbacktracking

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums that may contain duplicate values, return **all possible subsets** (the power set). The result must **not contain any duplicate subsets**. Two subsets are considered the same if they contain exactly the same multiset of elements, regardless of the order in which those elements appear. You may return the subsets in any order, and the elements within each subset may also be in any order. The empty subset [] must always be included in the result. For example, the arrays [1, 2] and [2, 1] represent the same subset and should only appear once. Because the input can contain repeated numbers, naively generating every subset would produce duplicates that must be filtered out.

Examples

Input: nums = [1, 2, 2]
Output: [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
Even though there are two 2's, the subset {2} only appears once and the subset {1, 2} only appears once. There are 6 distinct subsets in total.
Input: nums = [0]
Output: [[], [0]]
With a single element there are only two subsets: the empty set and the set containing that element.
Input: nums = [4, 1, 4]
Output: [[], [1], [1, 4], [1, 4, 4], [4], [4, 4]]
After accounting for the duplicate 4's, there are 6 unique subsets.

Constraints

  • `1 <= nums.length <= 10`
  • `-10 <= nums[i] <= 10`
  • The input may contain duplicate values.
  • The number of distinct subsets fits comfortably in memory.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More backtracking problems