Subsets II - Problem
Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Note: A subset is a selection of elements from the array, including the empty subset and the array itself.
Input & Output
Example 1 — Basic Case with Duplicates
$
Input:
nums = [1,2,2]
›
Output:
[[],[1],[1,2],[1,2,2],[2],[2,2]]
💡 Note:
The array contains duplicates. All unique subsets are: empty set, single elements [1] and [2], pairs [1,2] and [2,2], and the full array [1,2,2]. Note that [2] appears only once even though there are two 2s.
Example 2 — All Identical Elements
$
Input:
nums = [4,4,4]
›
Output:
[[],[4],[4,4],[4,4,4]]
💡 Note:
When all elements are identical, we get subsets of different lengths: empty, single element, pair, and triplet. No actual duplicates in the result.
Example 3 — No Duplicates
$
Input:
nums = [1,2,3]
›
Output:
[[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]
💡 Note:
When there are no duplicates in input, this behaves like the regular Subsets problem, generating all 2^3 = 8 possible subsets.
Constraints
- 1 ≤ nums.length ≤ 10
- -10 ≤ nums[i] ≤ 10
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array with duplicates: [1,2,2]
2
Process
Generate all unique subsets avoiding duplicates
3
Output
6 unique subsets (not 8 like regular subsets)
Key Takeaway
🎯 Key Insight: Sort first, then skip duplicates at the same recursion level to avoid duplicate subsets
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code