Every distinct ordering of numbers that may repeat. Sort first, then skip a copy whenever its twin to the left is still unused in this branch.
▼The problem
LeetCode 47 (Medium). Given a list of numbers that may contain duplicates, return all distinct permutations.
Examples (LeetCode's): [1,1,2] → [[1,1,2],[1,2,1],[2,1,1]]; [1,2,3] → all 6 permutations.
The solution
def permute_unique(nums):
nums.sort()
res, path = [], []
used = [False] * len(nums)
def back():
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
if i > 0 and nums[i] == nums[i-1] and not used[i-1]:
continue
used[i] = True
path.append(nums[i])
back()
path.pop()
used[i] = False
back()
return resTranscript
Permutations Two. You get a list of numbers, and some of them may repeat. Return every distinct ordering of the list, each one exactly once.
Take one, one, two. Three ducks, but just three line-ups: one one two, one two one, and two one one. Swapping the twin ones changes nothing. One, two, three has no twins, so all six orderings count.
The easy way: build every ordering, then drop the repeats with a set. One, one, two builds six to keep three. Eight ones? Over forty thousand built, and just one kept. Most of that work is thrown away.
The fix is to never build a repeat. First, sort, so twins stand side by side. Then fill the line slot by slot, as in plain permutations: pick an unused number, mark it used, recurse, then undo.
Now the one new rule. Skip a number when it equals the one before it, and that one is still unused. A twin may only go in after its older twin. So twins always go in order, and each line-up is built once.
In code: sort, then backtrack. When the path is full, save a copy. Otherwise try each index. Skip it if it's used, or if its older twin is still waiting. Mark it, add it, recurse, then take it back out.
Let's run one, one, two. Place the first one, the second one, then two: one one two. Back up. Two goes second, then the last one: one two one. Back at the start, the second one tries slot zero, but its twin is unused: skipped. Two goes first, then both ones in order: two one one. Under two, the second one is skipped again. Three line-ups, no repeats.
With no twins, there are n factorial line-ups, each copied in n steps: order n times n factorial time. Twins only shrink that. The path, the used flags and the recursion take order n space, plus the output.
Sort, keep twins in order, skip the waiting twin. That's Permutations Two.