Permutations
medium 24 minGenerating every ordering of a list is the backtracking pattern where order matters.
See it run
Every ordering of [1, 2, 3] with a used[] array, the n! decision tree, in-place swaps, Permutations II and next permutation.
Operations
used[] on [1, 2, 3]
Order matters, so every position may take any value not already in the path. Loop from 0 every time, skip the indices marked used, and save the path when it holds all n values.
Step 1 of 11
Empty path, nothing used
- 10
- 21
- 32
path
- _0
- _1
- _2
We want all 3! = 3 \times 2 \times 1 = 6 orderings of [1, 2, 3]. Start with an empty path and used = [F, F, F]. Each _ below is a position still to fill.
Step 1: Empty path, nothing used
def permute(nums): result, path = [], [] used = [False] * len(nums) def backtrack(): if len(path) == len(nums): result.append(path[:]) # a full arrangement: save a copy return for i in range(len(nums)): # always from 0, never from start if used[i]: continue # already in the path used[i] = True # lock path.append(nums[i]) # choose backtrack() # explore path.pop() # unchoose used[i] = False # unlock backtrack() return result- Time
- O(n · n!)
- Space
- O(n) path, flags and stack
- [1, 2]
- 2! = 2
- [1, 2, 3]
- 3! = 6
- [1, 2, 3, 4]
- 4! = 24
Five lines in the loop body, in mirror order: used[i] = True, append, recurse, pop, used[i] = False. If the undo half does not mirror the do half, something leaks.
In the real world
The same permutations doing real jobs. Pick one and step through it.
Alice, Bob and Cara stand in a line. [Alice, Bob] is a different photo from [Bob, Alice], so order matters: 3! = 6 photos.
Step 1 of 5
Three people, three spots
- Alice
- Bob
- Cara
line
- _
- _
- _
The photographer fills the line left to right. Anyone not yet standing is free to take the next spot.
Step 1: Three people, three spots
from itertools import permutationsfor line in permutations(["Alice", "Bob", "Cara"]): print(line) # 6 photosCommon mistakes
The bugs interviewers watch for, with the fix beside each.
Looping from start instead of 0
criticalA start index means only later values can follow, which is the subsets and combinations rule. It builds [1, 2, 3] but never [2, 1, 3]: you get one ordering instead of n!.
Wrongfor i in range(start, len(nums)): # combinations rule path.append(nums[i]) backtrack(i + 1) path.pop()Rightfor i in range(len(nums)): # every position sees every value if used[i]: continue used[i] = True; path.append(nums[i]) backtrack() path.pop(); used[i] = FalsePopping the path but not unlocking used[i]
criticalThe value leaves the path but stays marked as used, so no later branch can ever pick it again. For [1, 2, 3] only [1, 2, 3] comes out.
Wrongused[i] = Truepath.append(nums[i])backtrack()path.pop() # used[i] still TrueRightused[i] = Truepath.append(nums[i])backtrack()path.pop()used[i] = False # undo bothSaving the path, not a copy
criticalpathis one list that keeps changing. Appending it stores a reference, so after backtracking every saved answer is the same empty list.Wrongresult.append(path) # n! references to one listRightresult.append(path[:]) # a snapshotPermutations II without the used[i - 1] check
majorSkipping every value equal to its left neighbour also blocks the second copy when the first is already in the path, so [1, 1, 2] loses every answer with both 1s. Forgetting to sort breaks it too: copies are not neighbours.
Wrongif i > 0 and nums[i] == nums[i - 1]: continue # [1, 1, 2] returns []Rightnums.sort()if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]: continue # only repeats at this levelForgetting to swap back
majorIn the in-place version each branch must hand the array back unchanged. Without the second swap later branches start from a scrambled array, so some orderings repeat and others never appear.
Wrongnums[start], nums[i] = nums[i], nums[start]backtrack(start + 1) # array left scrambledRightnums[start], nums[i] = nums[i], nums[start]backtrack(start + 1)nums[start], nums[i] = nums[i], nums[start] # restoreNext permutation with > instead of >=
minorWith repeated values a strict comparison stops on an equal pair. On [2, 2, 1] the pivot lands on the first 2, which has no bigger value to its right, and the result is [2, 1, 2]: smaller than the input, instead of wrapping to [1, 2, 2].
Wrongwhile i >= 0 and nums[i] > nums[i + 1]: i -= 1...while nums[j] < nums[i]: j -= 1Rightwhile i >= 0 and nums[i] >= nums[i + 1]: i -= 1...while nums[j] <= nums[i]: j -= 1
Interview tips
How to explain it
- Order matters, so each position can take any unused value: n choices, then n - 1, down to 1, which is n!.
- Each of the n! answers is copied in O(n), so O(n · n!) time; the path, flags and stack are O(n).
- Offer the alternatives: in-place swaps (no extra arrays, unsorted output) and next permutation (iterative, sorted output).
During the interview
- Ask whether the input can repeat values; if so, it is Permutations II and you need sort plus the skip rule.
- Check n: up to about 8 to 10 is fine for n!. Bigger means the problem wants counting, DP or a greedy rule.
- If only the k-th or the next arrangement is wanted, do not generate them all: use factorial digits or next permutation.
Memory tricks
- ZERO-USED: loop from zero, track what is used.
- The used array dance: lock, choose, explore, unchoose, unlock.
- Duplicates: a copy may go only if its left twin is already in the path.
- Next permutation: dip, swap, reverse.
Watch out
- Undo both the path and the flag after every recursive call.
- Copy the path when you save it.
- The swap version's output order is not lexicographic.