Subsets II
List every different subset of an array whose values may repeat, each subset once.
Given an array of integers nums
Example 1
Output: [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
Example 2
Output: [[], [0]]
The Idea
Picture a fruit bowl with one apple and two pears. Which handfuls could you take from it, if taking nothing also counts? Write the apple as 1 and each pear as 2, and the bowl becomes Example 1, nums = [1, 2, 2]
Each of the three fruits is either taken or left, so there are 2 ร 2 ร 2 = 8 ways to grab a handful. But a handful with the first pear looks just like one with the second pear. The apple with a pear comes up twice, and so does a pear on its own. That leaves six different handfuls, the six subsets in the answer. So how do we list those six without building all eight and throwing two away?
Sorting is a good start: equal values then sit side by side, as in 1, 2, 2. Now build a subset one number at a time, always taking the next number from the positions after the last one taken. Every subset met along the way is an answer, the empty one included. For repeated values, one rule is enough: for each place in the subset (its first number, its second number, and so on), try each value once.
Look at the picture below. Each blue box is a subset, and the teal text inside it, "saved: answer 1" to "saved: answer 6", gives the order in which it is saved. The lines are the choices, labelled with the number taken, and an orange dashed box is a choice that is skipped.
From the empty subset [ ][2][ ][1][1, 2]
Now look at the line labelled "take second 2" under [2][2, 2][1, 2][1, 2, 2]
After saving [1, 2, 2]
Solution Approach
Turning that tree into code means settling how to build and save the subsets and how to skip a repeated value, and seeing why skipping beats removing the repeats at the end.
Building and saving the subsets
How does the code walk through the picture? A method buildsubsetstartbuildsubset
Then a loop tries each index istartnums[i]subsetbuildi + 1startbuild
Skipping a repeated value
How does the loop know that a 2 was already tried for this place? After the sort, the two pears are neighbours, so the earlier 2 is at i - 1i > start && nums[i] == nums[i - 1]
The part i > start[2, 2]i == start
Removing repeats at the end instead
Why not build all subsets as if every number were different, and put them in a HashSetbuild[2, 2, 2]
Java Solution
The method subsetsWithDup
- First, sort the input array with
, so equal values sit next to each other.Arrays.sort(nums) - Create the list
for the answers, and start the search withresult : an emptybuild(nums, 0, new ArrayList<>(), result) , and picks starting at index 0.subset - In
, add a copy ofbuild tosubset . The copy is needed becauseresult itself keeps changing as the search goes on.subset - Then a loop moves
fromi to the end of the array, and skips a value equal to the one before it whenstart .i > start - For any other
, addi tonums[i] and callsubset with startbuild . Then take the last number offi + 1 again, which frees the place for the next number.subset - When the first call of
returns,build returnssubsetsWithDup .result
The main{4, 1, 4}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SubsetsII {
public static List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums); // equal values become neighbours
List<List<Integer>> result = new ArrayList<>();
build(nums, 0, new ArrayList<>(), result);
return result;
}
private static void build(int[] nums, int start, List<Integer> subset,
List<List<Integer>> result) {
result.add(new ArrayList<>(subset)); // every subset built is an answer
for (int i = start; i < nums.length; i++) {
if (i > start && nums[i] == nums[i - 1]) {
continue; // same value already tried for this place
}
subset.add(nums[i]);
build(nums, i + 1, subset, result); // later positions only
subset.remove(subset.size() - 1); // take it back, try the next value
}
}
public static void main(String[] args) {
System.out.println(subsetsWithDup(new int[] {1, 2, 2}));
System.out.println(subsetsWithDup(new int[] {0}));
System.out.println(subsetsWithDup(new int[] {2, 2, 2}));
int[] mixed = {4, 1, 4};
System.out.println(subsetsWithDup(mixed) + " from " + Arrays.toString(mixed));
System.out.println(subsetsWithDup(new int[] {}));
}
}
Running it prints:
[[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
[[], [0]]
[[], [2], [2, 2], [2, 2, 2]]
[[], [1], [1, 4], [1, 4, 4], [4], [4, 4]] from [1, 4, 4]
[[]]
Look at the first line: the six subsets come out in the same order as answers 1 to 6 in the picture. Three 2s give [[], [2], [2, 2], [2, 2, 2]]
The line for {4, 1, 4}from [1, 4, 4]Arrays.sortnums.clone()[[]]
Why does the check say i > starti > 0i > 0[[], [1], [1, 2], [2]][1, 2, 2][2, 2][[], [2]]
Complexity
The work is one call of buildresult
- Time: O(n ยท 2n) in the worst case, because when all n values differ, each is in a subset or not, giving 2n subsets that each take up to n steps to copy. Repeated values only remove branches, and the sort, O(n log n), is small next to that.
- Space: O(n) besides the output, because each call moves
past the number it took, so at most n + 1 calls are open at once andstart holds at most n numbers.subset
The same skip rule keeps each group once in