Subsets II - Problem
Subsets II challenges you to generate the power set (all possible subsets) of an array that may contain duplicate elements. Unlike the classic subsets problem, here you must ensure that no duplicate subsets appear in your result.
Given an integer array
Goal: Generate all unique subsets from an array with duplicates
Input: Integer array that may contain duplicate values
Output: List of all unique subsets (in any order)
Given an integer array
nums with possible duplicates, return all unique subsets. The order of subsets doesn't matter, but each subset should appear exactly once. For example, if your array is [1, 2, 2], you should include [1, 2] only once, not twice.Goal: Generate all unique subsets from an array with duplicates
Input: Integer array that may contain duplicate values
Output: List of all unique subsets (in any order)
Input & Output
example_1.py โ Basic case with duplicates
$
Input:
[1,2,2]
โบ
Output:
[[],[1],[1,2],[1,2,2],[2],[2,2]]
๐ก Note:
The array contains duplicate 2's. We generate all unique subsets: empty set, single elements [1] and [2], pairs [1,2] and [2,2], and the full set [1,2,2]. Note that [1,2] appears only once even though it can be formed in multiple ways.
example_2.py โ Multiple duplicates
$
Input:
[4,4,4,1,4]
โบ
Output:
[[],[1],[1,4],[1,4,4],[1,4,4,4],[1,4,4,4,4],[4],[4,4],[4,4,4],[4,4,4,4]]
๐ก Note:
With four 4's and one 1, we can form subsets with 0-4 copies of 4, each optionally including the 1. After sorting, duplicates are handled systematically.
example_3.py โ No duplicates edge case
$
Input:
[1,2,3]
โบ
Output:
[[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]
๐ก Note:
When there are no duplicates, this behaves like the classic subsets problem, generating all 2^3 = 8 possible subsets.
Constraints
- 1 โค nums.length โค 10
- -10 โค nums[i] โค 10
- The solution set must not contain duplicate subsets
Visualization
Tap to expand
Understanding the Visualization
1
Line Up by Skill
Sort players by skill level to group identical players together
2
Make Decisions
For each skill level, decide how many players of that skill to include
3
Skip Smart
When excluding a player, exclude all players with identical skills to avoid duplicate teams
4
Record Teams
Add each unique team composition to your final roster
Key Takeaway
๐ฏ Key Insight: Sorting groups duplicates together, allowing us to systematically skip identical elements and generate only unique subsets efficiently.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code