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
Subsets II - Handling Duplicates INPUT Integer Array (with duplicates) 1 idx: 0 2 idx: 1 2 idx: 2 duplicate! nums = [1, 2, 2] Find ALL unique subsets Power set without duplicates Total subsets: 6 (Not 8 due to duplicates) ALGORITHM STEPS 1 Sort Array Group duplicates together [1,2,2] (already sorted) 2 Backtracking Include or exclude element 3 Skip Duplicates If nums[i] == nums[i-1] and prev was skipped 4 Add to Result Add current subset Decision Tree (simplified) { } +1 -1 Skip dup when prev skipped FINAL RESULT All Unique Subsets: [ ] empty [1] [1, 2] [1, 2, 2] [2] [2, 2] OK - 6 Unique Subsets No duplicate subsets! Key Insight: Sort first to group duplicates. When backtracking, skip a duplicate element if the previous identical element was NOT included. This prevents generating duplicate subsets like [2] twice. Condition: if (i > start && nums[i] == nums[i-1]) continue; TutorialsPoint - Subsets II | Optimal Backtracking Solution - O(n * 2^n)
Asked in
Facebook 35 Amazon 28 Microsoft 22 Google 18
185.0K Views
Medium Frequency
~15 min Avg. Time
3.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen