Permutations II (LeetCode 47): Solution and Explanation

Medium
Array
Backtracking
Sorting

Given an array nums of up to 8 integers that may repeat, return every distinct permutation exactly once, in any order.

Intuition

Plain permutation backtracking fills one slot at a time with any tile that is not already in the path. With [1,1,2] that produces 6 orderings, but swapping the two 1s does not change the sequence, so half of them are copies.

A copy is born at one specific moment: when two equal tiles are both offered for the same slot at the same depth. Whichever of them you pick, the rest of the search below is identical, so the second pick can only rebuild what the first already built.

Sorting puts equal values next to each other, which lets us tell the copies apart by index. Now add one rule: a copy may be placed only if its left twin is already in the path. If the left twin is unused, it has already been tried in this slot, so skip.

The effect is that equal values always enter the path in left to right order. Every distinct sequence corresponds to exactly one such order, so each one is generated once, with no hash set of results needed.

Approach: Sort, then backtrack with a twin-skip rule

  1. Sort nums so equal values are adjacent.
  2. Keep a path and a used array, both empty and all false at first.
  3. If path has n values, copy it into the result and return.
  4. Otherwise loop i over every index. Skip i if used[i] is true.
  5. Also skip i if i > 0, nums[i] == nums[i - 1] and used[i - 1] is false. The left twin already tried this value in this slot.
  6. Otherwise mark used[i], push nums[i], recurse, then pop and unmark to try the next tile.

Step-by-step example

nums = [1,1,2]
  1. Sorting leaves [1,1,2]. Call the tiles 1a, 1b and 2.
  2. Slot 1 takes 1a. Slot 2 skips 1a (used) and takes 1b, since its twin 1a is in the path. Slot 3 takes 2: record [1,1,2].
  3. Back out of slot 3 and slot 2. Slot 2 now tries 2, and slot 3 takes 1b: record [1,2,1].
  4. Back out to slot 1 and free 1a. Slot 1 now looks at 1b, but its twin 1a is unused, so placing 1b here would repeat the 1a branch. Skip it.
  5. Slot 1 takes 2. Slot 2 takes 1a, then slot 3 takes 1b: record [2,1,1]. Inside, 1b was again skipped at slot 2 because 1a was free.
  6. The search ends with 3 permutations: [[1,1,2],[1,2,1],[2,1,1]].

Code: Python, Java, C++

1class Solution:
2    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
3        nums.sort()
4        res = []
5        path = []
6        used = [False] * len(nums)
7
8        def backtrack():
9            if len(path) == len(nums):
10                res.append(path[:])
11                return
12            for i in range(len(nums)):
13                if used[i]:
14                    continue
15                if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
16                    continue
17                used[i] = True
18                path.append(nums[i])
19                backtrack()
20                path.pop()
21                used[i] = False
22
23        backtrack()
24        return res
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n * n!)

In the worst case all values are distinct and there are n! permutations, each copied in O(n). Duplicates only shrink the tree.

Space

O(n)

The recursion depth, the path and the used array are all size n. The output itself is not counted.

Other approaches

Generate all, deduplicate with a set (time O(n * n!), space O(n * n!))

Run the plain permutation search and store each result as a tuple in a hash set. It is correct but explores every duplicate branch and pays memory for the set.

Counter-based backtracking (time O(n * n!), space O(n))

Count each distinct value, then fill slots by choosing a value with a positive count. Equal values are never offered twice in one slot, so no skip rule is needed.

Next permutation in a loop (time O(n * n!), space O(1))

Sort, then repeatedly apply the next-permutation step until the sequence wraps around. Next permutation naturally skips equal arrangements, so each distinct one appears once.

Common mistakes

  • Forgetting to sort. The twin rule only compares neighbors, so equal values must be adjacent.
  • Using used[i - 1] instead of not used[i - 1]. Both versions give correct output, but not used prunes at the highest level and is the one that is easy to explain. Mixing them up while reasoning leads to wrong proofs.
  • Appending path itself instead of a copy, so every stored result is the same list that later gets emptied.
  • Not resetting used[i] after the recursive call, which hides tiles from later branches.

Frequently asked questions

Why does the rule check that the left twin is unused?

If the left twin is unused at this slot, it was already tried here earlier in the same loop and its whole subtree is done. Placing the right twin now would build the same subtree again. If the left twin is used, it sits in an earlier slot, and placing the right twin here is a new arrangement.

Does used[i - 1] (without not) also work?

Yes, it forces equal copies into right to left order instead, which is also unique. It prunes later in the tree, though, so it explores more dead branches before giving up.

How many permutations can there be?

With 8 distinct values there are 8! = 40,320. With repeats, divide by the factorial of each value's count, for example 8 values made of four 1s and four 2s give 70.

Is a set of results ever needed?

No. With the array sorted and the twin rule in place, each distinct permutation is produced exactly once.