Subsets II (LeetCode 90): Solution and Explanation
Given an array that may contain repeated numbers, return every possible subset without listing the same subset twice. The order of subsets in the output does not matter.
Watch it run step by step
Try your own input and write the code →Intuition
Without duplicates, generating subsets is a clean binary decision: for each element, either include it or leave it out, giving 2^n subsets. With duplicates, that same process produces repeats. For [1,2,2], picking the first 2 and skipping the second gives [1,2], and skipping the first 2 while picking the second also gives [1,2]. A brute force fix is to generate everything and deduplicate with a set of tuples, but that wastes time building subsets you then throw away.
The trick is to sort first so equal values sit next to each other, then think of a run of equal values as a single choice of how many copies to take. For a run of two 2s, the distinct options are zero, one or two copies. The include-or-skip recursion produces those options naturally as long as you enforce one rule: once you decide to skip a value, you skip every remaining copy of it too.
Why does that rule work? On the include branch you take the current copy and recurse to the next index, which may be another copy, so you can build up one copy, two copies and so on. On the exclude branch you jump past all the remaining equal values, which represents taking no more copies. That way each count of a repeated value is generated exactly once, and no duplicate subset is ever built.
The reference code expresses this with a while loop that advances i over equal neighbors before making the exclude call. Every leaf of the recursion, reached when i equals the array length, is a unique subset.
Approach: Sort and backtrack with duplicate skipping
- Sort
numsso that equal values are adjacent. - Define
backtrack(i, subset). Wheni == len(nums), append a copy ofsubsettoresand return. - Include branch: append
nums[i]tosubset, callbacktrack(i + 1, subset), then pop it to undo the choice. - Before the exclude branch, advance
iwhilenums[i] == nums[i + 1], so the skip jumps over every copy of this value. - Exclude branch: call
backtrack(i + 1, subset)with the value left out. - Start with
backtrack(0, [])and returnres.
Step-by-step example
nums = [1,2,2]
- The array is already sorted. Include 1, then include the first 2, then include the second 2, reaching the end and recording [1,2,2].
- Back at index 2 with [1,2], there is no duplicate ahead, so the exclude branch records [1,2].
- Back at index 1 with [1], the exclude branch first skips from index 1 to index 2 because both are 2, then recurses from index 3 and records [1].
- Back at index 0, exclude 1. With [] at index 1, include 2 and then 2 again to record [2,2], then exclude the second 2 to record [2].
- At index 1 with [], the exclude branch skips both 2s and records [].
- The result is [[1,2,2],[1,2],[1],[2,2],[2],[]], six subsets with no repeats.
Code: Python, Java, C++
1class Solution:
2 def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
3 res = []
4 nums.sort()
5
6 def backtrack(i, subset):
7 if i == len(nums):
8 res.append(subset[::])
9 return
10
11 # All subsets that include nums[i]
12 subset.append(nums[i])
13 backtrack(i + 1, subset)
14 subset.pop()
15
16 # All subsets that don't include nums[i]
17 while i + 1 < len(nums) and nums[i] == nums[i + 1]:
18 i += 1
19 backtrack(i + 1, subset)
20
21 backtrack(0, [])
22 return res1class Solution {
2 public List<List<Integer>> subsetsWithDup(int[] nums) {
3 Arrays.sort(nums);
4 List<List<Integer>> res = new ArrayList<>();
5 backtrack(0, nums, new ArrayList<>(), res);
6 return res;
7 }
8
9 private void backtrack(int i, int[] nums, List<Integer> subset, List<List<Integer>> res) {
10 if (i == nums.length) {
11 res.add(new ArrayList<>(subset));
12 return;
13 }
14
15 subset.add(nums[i]);
16 backtrack(i + 1, nums, subset, res);
17 subset.remove(subset.size() - 1);
18
19 while (i + 1 < nums.length && nums[i] == nums[i + 1]) {
20 i++;
21 }
22 backtrack(i + 1, nums, subset, res);
23 }
24}1class Solution {
2public:
3 vector<vector<int>> subsetsWithDup(vector<int>& nums) {
4 sort(nums.begin(), nums.end());
5 vector<vector<int>> res;
6 vector<int> subset;
7 backtrack(0, nums, subset, res);
8 return res;
9 }
10
11 void backtrack(int i, vector<int>& nums, vector<int>& subset, vector<vector<int>>& res) {
12 if (i == nums.size()) {
13 res.push_back(subset);
14 return;
15 }
16
17 subset.push_back(nums[i]);
18 backtrack(i + 1, nums, subset, res);
19 subset.pop_back();
20
21 while (i + 1 < nums.size() && nums[i] == nums[i + 1]) {
22 i++;
23 }
24 backtrack(i + 1, nums, subset, res);
25 }
26};Time and space complexity
O(n × 2^n)
In the worst case all values are distinct and there are 2^n subsets. Copying each subset into the result costs up to O(n), and sorting adds only O(n log n).
O(n)
The recursion depth and the working subset list are at most n long. The output itself is not counted as extra space.
Other approaches
Iterative build with duplicate handling (time O(n × 2^n), space O(1) beyond output)
Start from [[]] and, for each sorted value, append it to existing subsets. When the value equals the previous one, only extend the subsets created in the previous round, which avoids repeats without recursion.
Generate all and deduplicate (time O(n × 2^n), space O(n × 2^n))
Sort, run the plain subsets algorithm, and store each subset as a tuple in a set. It is easy to write but always does the full 2^n work even when duplicates collapse most of it.
Common mistakes
- Forgetting to sort first. The skip loop only compares neighbors, so unsorted duplicates will slip through.
- Skipping duplicates on the include branch instead of the exclude branch, which loses subsets like [2,2].
- Appending
subsetitself instead of a copy. Later pops mutate the same list, and every stored result ends up empty. - Writing the skip loop without the
i + 1 < len(nums)bound, which reads past the end of the array.
Frequently asked questions
How do you avoid duplicate subsets without using a set?
Sort the array and, whenever you decide to exclude a value, skip all of its remaining copies as well. Each possible count of a repeated value is then generated exactly once.
What is the difference between Subsets and Subsets II?
The first version has distinct elements, so plain include or exclude recursion never repeats. This version allows duplicates, so it needs sorting and the skip rule to avoid producing the same subset twice.
What is the time complexity of Subsets II?
It is O(n × 2^n) in the worst case, when no values repeat. Duplicates only reduce the number of distinct subsets produced.
Why do we need to sort the array?
Sorting groups equal values together, so a single neighbor comparison can tell whether the next element is another copy. Without sorting, equal values could be far apart and the skip would miss them.