Subsets II

List every different subset of an array whose values may repeat, each subset once.

Given an array of integers nums, which may contain repeated values, return every subset of it. A subset is any selection of the numbers, from none of them to all of them, with each position used at most once. Two subsets with the same values count as one, so each must appear only once. The subsets can come in any order.

Example 1
Input: nums = [1, 2, 2]
Output: [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
Example 2
Input: nums = [0]
Output: [[], [0]]
Solution

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 handful is a subset.

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.

Choice tree for the sorted nums 1, 2, 2. From the empty subset the search takes 1 or the first 2 and skips the second 2. Under [1] it takes the first 2 and skips the second. Under [1, 2] and under [2], the second 2 is taken. The six boxes are saved as answers 1 to 6.

From the empty subset [ ], the search takes 1 or the first 2. Starting with the second 2 would only build [2] again, so the orange box "second 2 skipped" in the row under [ ] shows that it is not taken. Under [1], the same happens: the first 2 gives [1, 2], and the second 2 is skipped.

Now look at the line labelled "take second 2" under [2]. Here the first 2 already fills the first place, and the second 2 is the first value tried for the second place. So it is taken, and [2, 2] is found. In the same way, [1, 2] grows into [1, 2, 2].

After saving [1, 2, 2] as answer 4, nothing is left to add. The search takes back the second 2, then the first 2, then the 1, and tries the first 2 at the top instead. Taking fruits one at a time and putting the last one back to try another is called backtracking. Without repeated values, this is the Subsets problem, and skipping a repeated value is the one new part.

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 build gets the numbers taken so far in a list subset. It also gets start, the position in the sorted array where its choices begin. Since every box is an answer, build first saves a copy of subset into the answer list.

Then a loop tries each index i from start on. It adds nums[i] to subset, calls build again with i + 1 as the new start, and then removes that number. Each call of build is one blue box, and the calls it makes are the boxes under it.

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 - 1. The check is i > start && nums[i] == nums[i - 1], and a number that passes it is skipped.

The part i > start keeps [2, 2] in the answer. When i == start, nothing has been tried for this place yet, so the number is used even if the number before it is equal. That earlier number was taken for the previous place, not tried for this one.

Removing repeats at the end instead

Why not build all subsets as if every number were different, and put them in a HashSet, which keeps each list once? The result would be correct, yet every repeated branch would still be built before being thrown away. For Example 1, build is called 6 times with the skip rule and 8 times without it. For [2, 2, 2], it is 4 calls against 8, and the gap grows with every extra copy of a value.

Java Solution

The method subsetsWithDup works in these steps:

  1. First, sort the input array with Arrays.sort(nums), so equal values sit next to each other.
  2. Create the list result for the answers, and start the search with build(nums, 0, new ArrayList<>(), result): an empty subset, and picks starting at index 0.
  3. In build, add a copy of subset to result. The copy is needed because subset itself keeps changing as the search goes on.
  4. Then a loop moves i from start to the end of the array, and skips a value equal to the one before it when i > start.
  5. For any other i, add nums[i] to subset and call build with start i + 1. Then take the last number off subset again, which frees the place for the next number.
  6. When the first call of build returns, subsetsWithDup returns result.

The main method runs both examples, three 2s, the unsorted array {4, 1, 4} (printing the array again after the call), and an empty array.

Java
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:

Output
[[], [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]], one subset for each count of 2s from none to three.

The line for {4, 1, 4} ends with from [1, 4, 4]. Arrays.sort sorted the caller's own array, so a caller that needs the original order should pass nums.clone(). The empty array prints [[]], because the empty subset is saved before the loop starts.

Why does the check say i > start and not i > 0? With i > 0, a value equal to its left neighbour is skipped at every place, not only for a place where it was already tried. Running that version prints [[], [1], [1, 2], [2]] for Example 1, losing [1, 2, 2] and [2, 2], and only [[], [2]] for three 2s.

Complexity

The work is one call of build per subset saved, plus copying that subset into result.

  • 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 start past the number it took, so at most n + 1 calls are open at once and subset holds at most n numbers.

The same skip rule keeps each group once in Combination Sum II, where the numbers must also add up to a target.