Permutations II
List every different arrangement of an array's numbers when some of the numbers repeat.
Given an array of integers nums
Example 1
Output: [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
Example 2
Output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
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
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.
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][2][2, 1a]
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, permbooleanusedbuildbuild
Because buildbuildbuild
Removing repeats at the end
Why not build every row, as for distinct numbers, and drop the repeats with a HashSet
Telling the copies apart
Which copy of a value is "1a" and which is "1b"? Sorting the array answers that. After Arrays.sort(nums)[2, 1, 2, 1][1, 1, 2, 2]
The check that cuts a branch
How does "1b only after 1a" look in code? When buildinums[i] == nums[i - 1] && !used[i - 1]i > 0
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]!used[i - 1]build
: 55 calls with[1, 1, 1, 1, 2, 2] , 331 with!used[i - 1] , for the same 15 rows.used[i - 1]- Eight 1s: 9 calls with
, 2,781 with!used[i - 1] , for the single row.used[i - 1]
With !used[i - 1]used[i - 1]
Java Solution
The method permuteUnique
- First, sort the input array with
, so copies of a value sit next to each other. Create the listArrays.sort(nums) , and callresult with a newbuild array, all false, and an empty listused .perm - In
, whenbuild holds as many numbers asperm , the row is full. Add a copy of it tonums and return. It must be a copy, becauseresult keeps changing as cards are taken back.perm - Otherwise, a loop moves
over every position ofi . It skips a card whosenums is true, and a card whose earlier copy atused[i] is not yet in the row.i - 1 - For any other card, set
to true, addused[i] tonums[i] , and callperm for the next spot. When that call returns, remove the card from the end ofbuild and setperm back to false, so the loop can try the next card here.used[i] - When the first call to
returns, every row has been built, andbuild returnspermuteUnique .result
The main[2, 1, 2, 1]
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:
[[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]
Look at the third line. The input [2, 1, 2, 1][1, 1, 2, 2]Arrays.sort
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]]
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
, on top of the loops over n positions in the calls above it. Repeats shrink the count:result gave 6 rows instead of 24.[2, 1, 2, 1] - Space: O(n) besides the output, because
holds n flags,used at most n numbers, and the calls ofperm are nested at most n + 1 deep, one per spot plus the full row.build