Subsets II
Pattern: Subsets
Sort, then build subsets by choosing the next element to add from a start index. Every node of that tree is a subset. Skip a value equal to the previous one at the same depth, so equal values never start the same subtree twice.
The problem
Given an array of whole numbers that may contain repeats, return all its distinct subsets. For example, [1, 2, 2]
gives [], [1], [1, 2], [1, 2, 2], [2] and [2, 2] (not [2] twice).
The function name subsetsWithDup matches LeetCode. Use the link above for the exact statement and limits. Any order is
accepted, so the tests sort before comparing.
Think first
- Why does plain take-or-skip produce
[2]twice for[1, 2, 2]? - After sorting, where do equal values sit?
- At which point does choosing the second
2repeat what the first2already did?
Hints
Brute force, and why it fails
Generate all 2ⁿ subsets, sort each, and keep the distinct ones in a set: same time, more memory, and more work per
subset. The skip rule never creates a duplicate in the first place.
The key insight
Duplicates arise only when equal values start identical subtrees from the same node. Allowing only the first of them at each depth removes every repeat and keeps every distinct subset.
Dry run
| found | [] |
|---|
nums = [1, 2, 2], already sorted. The root records [].
The plan
sort a
function build(start, bag):
record a copy of bag
for i from start to n - 1:
if i > start and a[i] == a[i - 1]: continue
add a[i]; build(i + 1, bag); remove it
build(0, [])
Complexity
- Time
O(2ⁿ × n)- Space
O(n)
At most 2ⁿ subsets, each copied in O(n). The recursion is n deep.
Edge cases
- All equal, as in
[4, 4, 4]:[],[4],[4, 4],[4, 4, 4]. - No repeats: the same as Subsets.
- One element: two subsets.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
int[] a = nums.clone();
Arrays.sort(a); // equal values side by side
List<List<Integer>> out = new ArrayList<>();
build(a, 0, new ArrayList<>(), out);
return out;
}
private void build(int[] a, int start, List<Integer> cur, List<List<Integer>> out) {
out.add(new ArrayList<>(cur)); // every node of the tree is a subset
for (int i = start; i < a.length; i++) {
if (i > start && a[i] == a[i - 1]) continue; // the same value at the same depth: same subsets again
cur.add(a[i]);
build(a, i + 1, cur, out);
cur.remove(cur.size() - 1);
}
}
}C++
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<int> a = nums;
sort(a.begin(), a.end()); // equal values side by side
vector<vector<int>> out;
vector<int> cur;
build(a, 0, cur, out);
return out;
}
void build(vector<int>& a, size_t start, vector<int>& cur, vector<vector<int>>& out) {
out.push_back(cur); // every node of the tree is a subset
for (size_t i = start; i < a.size(); i++) {
if (i > start && a[i] == a[i - 1]) continue; // the same value at the same depth: same subsets again
cur.push_back(a[i]);
build(a, i + 1, cur, out);
cur.pop_back();
}
}
};Python
class Solution:
def subsetsWithDup(self, nums: list[int]) -> list[list[int]]:
a = sorted(nums) # equal values side by side
out = []
def build(start: int, cur: list) -> None:
out.append(cur[:]) # every node of the tree is a subset
for i in range(start, len(a)):
if i > start and a[i] == a[i - 1]:
continue # the same value at the same depth: same subsets again
cur.append(a[i])
build(i + 1, cur)
cur.pop()
build(0, [])
return outCommon mistakes
- Forgetting to sort.
- Skipping with
i > 0instead ofi > start, which also drops[2, 2]. - Removing duplicates afterwards with a set.