Subsets II
Generate all unique subsets from an array containing duplicate integers using sorting and sibling-level duplicate pruning.
01The 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.
| Input | Output | Why |
|---|---|---|
nums = [1, 2, 2] | [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]] | [1, 2] using first 2 is identical to [1, 2] using second 2; duplicates omitted |
nums = [0] | [[], [0]] | Single element |
Constraints: 1 <= nums.length <= 10, -10 <= nums[i] <= 10.
02How to spot it
- Similar to Subsets (#74), but
numscontains duplicate values. - If we do not prune, identical subsets like
[1, 2]will be produced multiple times. - Sorting
numsgroups identical values side-by-side. - If
nums[i] == nums[i - 1]andi > start,nums[i]is a duplicate choice at the same recursion level (sibling branch), so choosing it would mirror the previous branch.
So: sort + skip duplicate siblings (i > start && nums[i] == nums[i-1]).
03Pseudocode
sort nums
build(start, cur):
record a copy of cur
for i from start to n - 1:
if i > start and nums[i] == nums[i-1]:
continue
choose, build(i + 1), un-choose- Sort
numsso duplicates are adjacent. - Record
cur. - If
i > startandnums[i] == nums[i - 1], skip this choice. - Recurse with
i + 1, then backtrack.
04Watch it work
sorted nums
current subset
status
sorted
Sort array [1, 2, 2] to place identical values adjacent for duplicate pruning.
Pseudocode
- sort nums
- build(start, cur):
- record a copy of cur
- for i from start to n - 1:
- if i > start and nums[i] == nums[i-1]:
- continue
- choose, build(i + 1), un-choose
Variables
- sorted
- 1,2,2
05Step-by-step dry run
- 1
sorted nums
102122icurrent subset
status
sorted
Sort array [1, 2, 2] to place identical values adjacent for duplicate pruning.
sorted = 1,2,2
- 2
sorted nums
102122icurrent subset
status
recorded []
Record subset: [].
subset = total = 1
- 3
sorted nums
102122icurrent subset
10status
choose 1
Choose sorted[0] = 1. Current: [1]. Recurse with start = 1.
i = 0val = 1
- 4
sorted nums
102122icurrent subset
10status
recorded [1]
Record subset: [1].
subset = 1total = 2
- 5
sorted nums
102122icurrent subset
1021status
choose 2
Choose sorted[1] = 2. Current: [1, 2]. Recurse with start = 2.
i = 1val = 2
- 6
sorted nums
102122icurrent subset
1021status
recorded [1, 2]
Record subset: [1, 2].
subset = 1,2total = 3
- 7
sorted nums
102122icurrent subset
102122status
choose 2
Choose sorted[2] = 2. Current: [1, 2, 2]. Recurse with start = 3.
i = 2val = 2
- 8
sorted nums
102122current subset
102122status
recorded [1, 2, 2]
Record subset: [1, 2, 2].
subset = 1,2,2total = 4
- 9
sorted nums
102122icurrent subset
1021status
un-choose 2
Backtrack: un-choose 2. Restore to [1, 2].
popped = 2
- 10
sorted nums
102122icurrent subset
10status
un-choose 2
Backtrack: un-choose 2. Restore to [1].
popped = 2
- 11
sorted nums
102122icurrent subset
10status
skip duplicate 2
Duplicate at index 2 (value 2 == 2) on same recursion level! Skip to prevent duplicate subsets.
i = 2val = 2
- 12
sorted nums
102122icurrent subset
status
un-choose 1
Backtrack: un-choose 1. Restore to [].
popped = 1
- 13
sorted nums
102122icurrent subset
20status
choose 2
Choose sorted[1] = 2. Current: [2]. Recurse with start = 2.
i = 1val = 2
- 14
sorted nums
102122icurrent subset
20status
recorded [2]
Record subset: [2].
subset = 2total = 5
- 15
sorted nums
102122icurrent subset
2021status
choose 2
Choose sorted[2] = 2. Current: [2, 2]. Recurse with start = 3.
i = 2val = 2
- 16
sorted nums
102122current subset
2021status
recorded [2, 2]
Record subset: [2, 2].
subset = 2,2total = 6
- 17
sorted nums
102122icurrent subset
20status
un-choose 2
Backtrack: un-choose 2. Restore to [2].
popped = 2
- 18
sorted nums
102122icurrent subset
status
un-choose 2
Backtrack: un-choose 2. Restore to [].
popped = 2
- 19
sorted nums
102122icurrent subset
status
skip duplicate 2
Duplicate at index 2 (value 2 == 2) on same recursion level! Skip to prevent duplicate subsets.
i = 2val = 2
06Java solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SubsetsWithDup {
public static List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
build(nums, 0, new ArrayList<>(), res);
return res;
}
private static void build(int[] nums, int start, List<Integer> cur, List<List<Integer>> res) {
res.add(new ArrayList<>(cur));
for (int i = start; i < nums.length; i++) {
if (i > start && nums[i] == nums[i - 1]) continue;
cur.add(nums[i]);
build(nums, i + 1, cur, res);
cur.remove(cur.size() - 1);
}
}
public static void main(String[] args) {
int[] nums = {1, 2, 2};
System.out.println(subsetsWithDup(nums));
}
}[[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
07Why it works
The condition i > start is the cornerstone of this algorithm:
- When
i == start,nums[i]is the first element considered at this level. If it equals a duplicate in a deeper level, that's fine (e.g.[2, 2]is allowed). - When
i > start, we are considering an alternative candidate at the same branch level. Ifnums[i] == nums[i - 1], exploringnums[i]would create the exact same family of subsets thatnums[i - 1]already generated. Skipping it prunes the duplicate branch entirely.
08Time and space
- Time complexity:
O(n * 2^n). Sorting takesO(n log n). In the worst case with all distinct elements, it generates2^nsubsets. - Space complexity:
O(n)stack and temporary list memory.
09Edge cases
- All identical elements (e.g.
[2, 2, 2]): Produces exactly[[], [2], [2, 2], [2, 2, 2]]. - Negative duplicates (e.g.
[-1, -1]): Handled identically after sorting.
10Common mistakes
- Forgetting
i > startand writingi > 0 && nums[i] == nums[i - 1]. This wrongly prevents selecting duplicates down the recursive chain, making it impossible to produce[2, 2]. - Forgetting to sort. If
nums = [2, 1, 2], unsorted duplicates cannot be detected by comparingnums[i] == nums[i - 1].
11Other approaches
| Approach | Time | Space | Notes |
|---|---|---|---|
| Set of lists | O(n * 2^n) | O(n * 2^n) | Inefficient memory hashing |
| Sort + sibling pruning | O(n * 2^n) | O(n) stack | Optimal, zero duplicate generation |
12In the interview
13Check your understanding
Quiz · 2 questions
0 of 2 answered
1. Why is i > start necessary in addition to nums[i] == nums[i - 1]?
2. What happens if we forget to sort nums first?
14Solve it yourself
Try tracing nums = [4, 4, 4, 1, 4]:
- What does the array look like after sorting?
- How many total unique subsets are produced?