Permutations II

List every different arrangement of an array's numbers when some of the numbers repeat.

Given an array of integers nums in which the same value may appear more than once, return every different way to arrange all of its numbers in a row. Such an arrangement is called a permutation. Two arrangements that read the same count as one, and they can be returned in any order.

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

The Idea

Picture three number cards, 1, 2 and 3, that you lay out in a row. Any of the three can go first, then either of the two left, then the last one: 3 × 2 × 1 = 6 rows, the six lists of Example 2.

Now swap the 3 for a second 1, as in Example 1. You still hold three cards, but swapping the two 1s in a row gives a row that reads the same. Only three different rows remain: 1, 1, 2, then 1, 2, 1, then 2, 1, 1.

The Permutations problem, where all numbers differ, builds the rows one card at a time. It places a card, fills the rest of the row, then takes that card back and tries the next unused card in its place. Taking a card back out of the row to try another card in its spot is called backtracking.

Run that on the cards 1, 1, 2 and it builds six rows, each one twice. It tells the cards apart by their position, so to it the two 1s are different cards. Call them 1a and 1b. The rows "1a, 1b, 2" and "1b, 1a, 2" are two results for it, yet both print as 1, 1, 2. So how do we build each different row once, without building the twins at all?

Every row with 1b before 1a has a twin with the two 1s the other way round. Keep only the twin where 1a comes first, and every different row is built exactly once. As a rule for placing cards: 1b may be placed only when 1a is already in the row. Look at the picture below.

The choice tree for the cards 1a, 1b and 2. Placing 1b while 1a is not yet in the row is cut, at the top and under [2]. Three full rows remain: [1, 1, 2], [1, 2, 1] and [2, 1, 1].

Each box is the row so far, and each line is one card placed. At the top, the dashed orange branch "place 1b" ends in a box marked "cut: 1b before 1a", because 1a is not in the row yet. Under [1a], placing 1b is allowed, since 1a is already in the row. Under [2], placing 1b is cut again, and only [2, 1a] goes on.

The three teal boxes at the bottom are the full rows, labelled result 1 to result 3, and they are exactly the output of Example 1. With the rule the tree keeps 9 blue and teal boxes, counting the empty start. Without it, the tree has 16 boxes and six full rows.

Solution Approach

Turning that rule into code means settling three things: how to build the rows one card at a time, how to tell copies of a value apart, and how to write the rule as one check. Two other ideas come up along the way and turn out worse: removing repeats at the end, and the opposite check.

Building the rows one card at a time

How does the code place a card and later take it back? It keeps the row so far in a list, perm, and one flag per position in a boolean array, used, that is true while that card is in the row. A method build fills the next spot: it tries each unused card, places it, and calls build again for the spot after it.

Because build calls build again to fill the spot after the card it just placed, it is called recursive. Each call is one box in the picture, and each call that build makes is one line down to a box below. When a call returns, the card it placed comes off the row again, which is the backtracking step.

Removing repeats at the end

Why not build every row, as for distinct numbers, and drop the repeats with a HashSet, which would keep only one copy of each row? It gives the right answer, but it builds all the twins first. For eight equal numbers, that means building 40,320 rows to keep one.

Telling the copies apart

Which copy of a value is "1a" and which is "1b"? Sorting the array answers that. After Arrays.sort(nums), equal values sit next to each other, and the copy at the lower position plays the part of 1a. For [2, 1, 2, 1], sorting gives [1, 1, 2, 2]: the 1s at positions 0 and 1, the 2s at positions 2 and 3.

The check that cuts a branch

How does "1b only after 1a" look in code? When build considers the card at position i, it skips it if the card just before it has the same value and is not yet in the row. In code, that is nums[i] == nums[i - 1] && !used[i - 1], with i > 0 checked first, because position 0 has no card before it.

One check against the neighbour is enough even for three or more copies. With 1a, 1b and 1c, the check lets 1c in only after 1b, and 1b only after 1a, so the copies always enter the row in their sorted order.

The opposite check

What happens with used[i - 1] instead of !used[i - 1]? The answer stays correct, because the rule then forces the copies into the reverse order, last copy first. It is slower, though, because the cut comes deeper in the tree. Counting the calls of build in a separate run gave these numbers:

  • [1, 1, 1, 1, 2, 2]: 55 calls with !used[i - 1], 331 with used[i - 1], for the same 15 rows.
  • Eight 1s: 9 calls with !used[i - 1], 2,781 with used[i - 1], for the single row.

With !used[i - 1], a later copy is turned away right at the spot where it would jump ahead. With used[i - 1], the code first places the earlier copies and only finds out several spots down that the remaining copies cannot go in.

Java Solution

The method permuteUnique works in these steps:

  1. First, sort the input array with Arrays.sort(nums), so copies of a value sit next to each other. Create the list result, and call build with a new used array, all false, and an empty list perm.
  2. In build, when perm holds as many numbers as nums, the row is full. Add a copy of it to result and return. It must be a copy, because perm keeps changing as cards are taken back.
  3. Otherwise, a loop moves i over every position of nums. It skips a card whose used[i] is true, and a card whose earlier copy at i - 1 is not yet in the row.
  4. For any other card, set used[i] to true, add nums[i] to perm, and call build for the next spot. When that call returns, remove the card from the end of perm and set used[i] back to false, so the loop can try the next card here.
  5. When the first call to build returns, every row has been built, and permuteUnique returns result.

The main method runs both examples, the unsorted array [2, 1, 2, 1] with two pairs of copies, three equal numbers, and a single number.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PermutationsII {

    public static List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);                      // equal values become neighbours
        List<List<Integer>> result = new ArrayList<>();
        build(nums, new boolean[nums.length], new ArrayList<>(), result);
        return result;
    }

    private static void build(int[] nums, boolean[] used, List<Integer> perm,
                              List<List<Integer>> result) {
        if (perm.size() == nums.length) {
            result.add(new ArrayList<>(perm));  // a full arrangement: keep a copy
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i]) {
                continue;                       // this card is already in perm
            }
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;                       // a later copy may not go before an earlier one
            }
            used[i] = true;
            perm.add(nums[i]);
            build(nums, used, perm, result);
            perm.remove(perm.size() - 1);       // take the card back
            used[i] = false;
        }
    }

    public static void main(String[] args) {
        System.out.println(permuteUnique(new int[] {1, 1, 2}));
        System.out.println(permuteUnique(new int[] {1, 2, 3}));
        System.out.println(permuteUnique(new int[] {2, 1, 2, 1}));
        System.out.println(permuteUnique(new int[] {7, 7, 7}));
        System.out.println(permuteUnique(new int[] {5}));
    }
}

Running it prints:

Output
[[1, 1, 2], [1, 2, 1], [2, 1, 1]]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
[[1, 1, 2, 2], [1, 2, 1, 2], [1, 2, 2, 1], [2, 1, 1, 2], [2, 1, 2, 1], [2, 2, 1, 1]]
[[7, 7, 7]]
[[5]]

The first line lists the three rows of the picture, in the order of result 1 to result 3. With no repeated values, as in [1, 2, 3] on the second line, the check never fires and all six rows come out.

Look at the third line. The input [2, 1, 2, 1] was not sorted, yet its rows start with [1, 1, 2, 2], because Arrays.sort ran first. Its 24 orders of four cards shrink to six different rows, each printed once.

On the fourth line, the three 7s could be ordered in six ways, but the check lets them in only in sorted order, so [[7, 7, 7]] appears once. A single number, on the last line, gives one row of its own.

Complexity

The cost follows the number of rows built, since the check cuts every repeat before it grows.

  • Time: O(n · n!) in the worst case, because with n different numbers there are n! rows, and each row takes n steps to copy into result, on top of the loops over n positions in the calls above it. Repeats shrink the count: [2, 1, 2, 1] gave 6 rows instead of 24.
  • Space: O(n) besides the output, because used holds n flags, perm at most n numbers, and the calls of build are nested at most n + 1 deep, one per spot plus the full row.