Permutations
medium 24 minGenerating every ordering of a list is the backtracking pattern where order matters.
Video lesson · Chapter 1 of 9
Arrange the shadow play
Permutations in 75 seconds
1:24Reel
How it works
Step through the idea, or press Play.
Any unused value, every position. Loop from 0 each time and skip indices marked used; order matters, so earlier values come back
Understand it
Start here
Permutations as a coding pattern
A permutation is an arrangement where order matters: [Alice, Bob] and [Bob, Alice] are two different photos. The counting side (why there are , and nPr against nCr) is covered in Combinations vs permutations, and the choose, explore, unchoose rhythm in Backtracking. This page is about the code.
Quick recap before the patterns
n! arrangements
choices for the first spot, for the second, down to 1: .
Choose, explore, unchoose
Append, recurse, pop, the same template as Subsets. Permutations add one more thing to undo: the used flag.
Order matters
Subsets and Combinations only look forward with a start index. Permutations must let an earlier value come later, so they loop from 0.
The patterns on this page
| Pattern | Idea | Output order |
|---|---|---|
used[] backtracking | Loop from 0, skip used indices | Lexicographic |
| Remaining list | Pass the unused values down | Lexicographic |
| In-place swapping | Swap each candidate into position start | Not sorted |
| Permutations II | Sort, skip a twin whose left copy is unused | Lexicographic, no repeats |
| Next permutation | Dip, swap, reverse the suffix | One step at a time |
Pattern 1
The used[] array: loop from 0, skip what is taken
At every level the loop starts at index 0, because any value not yet placed may go in the next spot. A boolean array used remembers which indices are already in the path. When the path holds all values it is a complete arrangement: save a copy.
One call of backtrack()
def permute(nums): result, path = [], [] used = [False] * len(nums) def backtrack(): if len(path) == len(nums): result.append(path[:]) # full arrangement: save a copy return for i in range(len(nums)): # always from 0 if used[i]: continue # already in the path used[i] = True # 1. lock path.append(nums[i]) # 2. choose backtrack() # 3. explore path.pop() # 4. unchoose used[i] = False # 5. unlock backtrack() return resultprint(permute([1, 2, 3]))# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]Walkthrough
permute([1, 2, 3]) step by step
- 1
Start with 1
Position 1: index 0 is free, so try 1. Path
[1],used = [T, F, F]. - 2
Second position: try 2
Loop from 0 again: index 0 is used, skip it; index 1 (value 2) is free. Path
[1, 2],used = [T, T, F]. - 3
Complete the first permutation
Only index 2 (value 3) is free. Path length equals : save
[1, 2, 3]. - 4
Backtrack to find more
Remove 3, then 2, unlocking both. From
[1]try 3 instead of 2:[1, 3], then 2 is free again, giving[1, 3, 2]. - 5
All 6 permutations
Then 2 first (
[2, 1, 3],[2, 3, 1]) and 3 first ([3, 1, 2],[3, 2, 1]): arrangements, each value exactly once in each.
The used array dance
| Step | Code | Meaning |
|---|---|---|
| 1 | used[i] = True | Lock the value |
| 2 | path.append(nums[i]) | Add it to the path |
| 3 | backtrack() | Fill the remaining spots |
| 4 | path.pop() | Remove it from the path |
| 5 | used[i] = False | Unlock it for later branches |
[1, 2, 3] ever comes out.The tree
The decision tree has n! leaves
Decision tree for [1, 2, 3]
Branching shrinks by one per level
Compare the subsets tree, where every node is an answer and each node has a fixed shape. Here answers live only at depth $n$, and the loop at each node scans all indices even though only are free. A remaining list instead of used avoids the scan but copies lists, so the bound is the same.
Complexity
O(n · n!) time, O(n) extra space
How many calls
Total work
How big n can be
| n | Verdict | |
|---|---|---|
| 3 | 6 | instant |
| 5 | 120 | instant |
| 8 | 40,320 | fast |
| 10 | 3,628,800 | a few seconds in Python |
| 12 | 479,001,600 | too slow |
| 20 | about | never |
Pattern 2
In-place swapping: the array is the path
Positions before start are fixed. For each i from start to the end, swap nums[i] into position start, recurse with start + 1, then swap back. No path, no used array: the array itself holds the arrangement, and the prefix is the path.
One call of backtrack(start)
def permute(nums): nums = nums[:] # work on a copy result = [] def backtrack(start): if start == len(nums): result.append(nums[:]) return for i in range(start, len(nums)): nums[start], nums[i] = nums[i], nums[start] # bring nums[i] forward backtrack(start + 1) nums[start], nums[i] = nums[i], nums[start] # swap back backtrack(0) return resultprint(permute([1, 2, 3]))# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]used[] + path | In-place swap | |
|---|---|---|
| Loop range | range(0, n) with a used check | range(start, n) |
| Extra memory | path + flags + stack: | stack only: |
| Output order | Lexicographic (if input sorted) | Not sorted |
| Duplicates | Sort + skip rule works | Needs a set of values tried at each level |
| Prune by position | Easy: check before appending | Easy: check before recursing |
Permutations II
Duplicates: sort, skip when the previous twin is unused
Now nums may repeat values, and the answer must not repeat arrangements. On [1, 1, 2] the plain code returns 6 lists but only 3 are different, because swapping the two 1s changes nothing. Sort so equal values are neighbours, then in the loop skip nums[i] when i > 0, nums[i] == nums[i - 1] and used[i - 1] is False.
Decision tree for sorted [1, 1, 2]
def permute_unique(nums): nums = sorted(nums) # equal values side by side result, path = [], [] used = [False] * len(nums) def backtrack(): if len(path) == len(nums): result.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 # twin already tried at this level used[i] = True path.append(nums[i]) backtrack() path.pop() used[i] = False backtrack() return resultprint(permute_unique([1, 1, 2])) # [[1, 1, 2], [1, 2, 1], [2, 1, 1]]print(len(permute_unique([1, 1, 2, 2]))) # 6How many distinct arrangements
Deep dive
Why "left twin unused" means "same level"
The check on sorted [1, 1, 2], index 1 (the second 1)
| Where | used[0] | What it means | Decision |
|---|---|---|---|
Root, path [] | False | The first 1 was tried here and already unlocked | Skip |
Under [1] | True | The first 1 sits one level up | Allowed: builds [1, 1, ...] |
Under [2] | False | The first 1 was tried at this level | Skip |
Under [2, 1] | True | The first 1 is in the path | Allowed: builds [2, 1, 1] |
Pattern 3
Next permutation: the array view
- 1Diprightmost i with nums[i] < nums[i+1]
- 2Swapwith the smallest bigger value to its right
- 3Reversethe suffix after i
[1, 3, 5, 4, 2]: the dip is 3 (the suffix 5, 4, 2 is decreasing), swap with 4 to get [1, 4, 5, 3, 2], reverse the suffix: [1, 4, 2, 3, 5].
def next_permutation(nums): i = len(nums) - 2 while i >= 0 and nums[i] >= nums[i + 1]: i -= 1 # find the dip if i >= 0: j = len(nums) - 1 while nums[j] <= nums[i]: j -= 1 # smallest value bigger than nums[i] nums[i], nums[j] = nums[j], nums[i] nums[i + 1:] = reversed(nums[i + 1:])a = [1, 3, 5, 4, 2]next_permutation(a)print(a) # [1, 4, 2, 3, 5]a = [1, 1, 2]seen = []for _ in range(3): seen.append(a[:]) next_permutation(a)print(seen, a) # 3 distinct, then back to [1, 1, 2]Every arrangement of [1, 2, 3] by repeated calls
| Before | Dip | Swap with | After |
|---|---|---|---|
| [1, 2, 3] | 2 | 3 | [1, 3, 2] |
| [1, 3, 2] | 1 | 2 | [2, 1, 3] |
| [2, 1, 3] | 1 | 3 | [2, 3, 1] |
| [2, 3, 1] | 2 | 3 | [3, 1, 2] |
| [3, 1, 2] | 1 | 2 | [3, 2, 1] |
| [3, 2, 1] | none | - | [1, 2, 3] (wrap) |
Family
Subsets, combinations, permutations
| Problem | Loop | Save when | Count | Page |
|---|---|---|---|---|
| Subsets | range(start, n), recurse i + 1 | Every node | Subsets | |
| Combinations of size | range(start, n), recurse i + 1 | len(path) == k | Combinations | |
| Permutations | range(0, n) with used | len(path) == n | this page | |
| Arrangements of size | range(0, n) with used | len(path) == k | this page, stop early | |
| Permutations II | range(0, n), used, twin skip | len(path) == n | this page |
When only the k-th arrangement is wanted, skip the enumeration: each block of arrangements shares a first value, so dividing by picks it, and the remainder picks the rest. This is the factorial number system.
The k-th permutation from factorial digits
from math import factorialdef kth_permutation(n, k): values = list(range(1, n + 1)) k -= 1 # 0-based out = [] for size in range(n, 0, -1): block = factorial(size - 1) # arrangements per first value d, k = divmod(k, block) out.append(str(values.pop(d))) return "".join(out)print(kth_permutation(4, 9)) # 2314print(kth_permutation(3, 6)) # 321Choosing
Which version to write
Pick a pattern
Enumerate permutations when
- The problem asks for all orderings, schedules or arrangements.
- is small, around 8 to 10 or less.
- Each placement can be checked as you go, so pruning cuts the tree (N-Queens, beautiful arrangements).
- The input may repeat values and you can sort it first.
Look for something else when
- Only a count is wanted: or the multinomial formula.
- Only the next or the k-th arrangement is wanted.
- The question is whether some permutation exists inside a string: sliding window counts.
- is large: even is over six billion arrangements.
Recap
Key takeaways
Key points
- n distinct values have n! orderings; listing them costs O(n · n!) time, which is optimal, and O(n) extra space.
- used[] version: loop from 0 every time, skip used indices, save when len(path) == n.
- Undo both after the call: path.pop() and used[i] = False.
- Always save a copy: result.append(path[:]).
- In-place swapping: swap nums[i] into position start, recurse on start + 1, swap back. Output is not sorted.
- Permutations II: sort, then skip nums[i] when it equals nums[i - 1] and used[i - 1] is False.
- Distinct arrangements with repeats: n! divided by the factorial of each value's count.
- Next permutation: find the dip from the right, swap with the smallest bigger value to its right, reverse the suffix.