AlgoViz

Permutations

medium 24 min

Generating every ordering of a list is the backtracking pattern where order matters.

Video lesson · Chapter 1 of 9

Arrange the shadow play

0:00 / 6:34

Permutations in 75 seconds

1:24Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

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 n!n!, 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

    nn choices for the first spot, n−1n - 1 for the second, down to 1: 3!=3×2×1=63! = 3 \times 2 \times 1 = 6.

  • 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

PatternIdeaOutput order
used[] backtrackingLoop from 0, skip used indicesLexicographic
Remaining listPass the unused values downLexicographic
In-place swappingSwap each candidate into position startNot sorted
Permutations IISort, skip a twin whose left copy is unusedLexicographic, no repeats
Next permutationDip, swap, reverse the suffixOne 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 nn values it is a complete arrangement: save a copy.

One call of backtrack()

The only differences from subsets: the loop starts at 0, there is a used check, and a path is saved only when it is full.
Python
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]]
The template to memorise. The loop body is the used array dance: lock, choose, explore, unchoose, unlock.
Edit and run it in your browser

Walkthrough

permute([1, 2, 3]) step by step

  1. 1

    Start with 1

    Position 1: index 0 is free, so try 1. Path [1], used = [T, F, F].

  2. 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. 3

    Complete the first permutation

    Only index 2 (value 3) is free. Path length equals nn: save [1, 2, 3].

  4. 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. 5

    All 6 permutations

    Then 2 first ([2, 1, 3], [2, 3, 1]) and 3 first ([3, 1, 2], [3, 2, 1]): 3!=63! = 6 arrangements, each value exactly once in each.

The used array dance

StepCodeMeaning
1used[i] = TrueLock the value
2path.append(nums[i])Add it to the path
3backtrack()Fill the remaining spots
4path.pop()Remove it from the path
5used[i] = FalseUnlock it for later branches
Steps 4 and 5 mirror steps 2 and 1. Forget step 5 and only [1, 2, 3] ever comes out.

The tree

The decision tree has n! leaves

Decision tree for [1, 2, 3]

Each level fills one position. The root has 3 branches, level 1 nodes have 2, level 2 nodes have 1: the last position is forced. Only the 6 green leaves are answers.

Branching shrinks by one per level

n⋅(n−1)⋅(n−2)⋯2⋅1=∏k=1nk=n!n \cdot (n-1) \cdot (n-2) \cdots 2 \cdot 1 = \prod_{k=1}^{n} k = n!
A node at depth dd has n−dn - d unused values, so n−dn - d children. Multiplying the branching factors down any path gives the number of leaves.

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 nn indices even though only n−dn - d 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

∑k=0nn!(n−k)!  =  n!∑j=0n1j!  <  e⋅n!(n=3:  1+3+6+6=16)\sum_{k=0}^{n} \frac{n!}{(n-k)!} \;=\; n! \sum_{j=0}^{n} \frac{1}{j!} \;<\; e \cdot n! \qquad (n = 3:\; 1 + 3 + 6 + 6 = 16)
Depth kk has n!(n−k)!\frac{n!}{(n-k)!} nodes. The whole tree is less than e≈2.72e \approx 2.72 times the number of leaves, so the call count is O(n!)O(n!).

Total work

T(n)=O(n!)⏟calls⋅O(n)⏟loop or copy per call=O(n⋅n!),S(n)=O(n)⏟path+O(n)⏟used+O(n)⏟stack=O(n)T(n) = \underbrace{O(n!)}_{\text{calls}} \cdot \underbrace{O(n)}_{\text{loop or copy per call}} = O(n \cdot n!), \qquad S(n) = \underbrace{O(n)}_{\text{path}} + \underbrace{O(n)}_{\text{used}} + \underbrace{O(n)}_{\text{stack}} = O(n)
The output alone holds n⋅n!n \cdot n! numbers, so no method that lists every permutation can be faster. Storing them all needs O(n⋅n!)O(n \cdot n!) memory; a generator avoids that.

How big n can be

nn!n!Verdict
36instant
5120instant
840,320fast
103,628,800a few seconds in Python
12479,001,600too slow
20about 2.4×10182.4 \times 10^{18}never
n!n! passes 2n2^n at n=4n = 4 (24>1624 > 16) and never looks back. A limit like n≤8n \le 8 in a problem is a strong hint to enumerate permutations.

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)

Swapping brings a later value forward, so every value still gets a turn at every position even though the loop starts at start.
Python
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]]
Same 6 answers, different order: [3, 2, 1] comes before [3, 1, 2].
Edit and run it in your browser
used[] + pathIn-place swap
Loop rangerange(0, n) with a used checkrange(start, n)
Extra memorypath + flags + stack: O(n)O(n)stack only: O(n)O(n)
Output orderLexicographic (if input sorted)Not sorted
DuplicatesSort + skip rule worksNeeds a set of values tried at each level
Prune by positionEasy: check before appendingEasy: check before recursing
Both are O(n⋅n!)O(n \cdot n!). Interviewers accept either; the used version is easier to extend to Permutations II.

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]

The dashed branches would rebuild everything the first 1 already built at that level. Below [1], the second 1 is allowed because its twin is in the path. Result: 3 arrangements.
Python
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])))   # 6
One extra condition compared with permute, plus the sort.
Edit and run it in your browser

How many distinct arrangements

n!c1! c2!⋯cm!,[1,1,2]:  3!2! 1!=3,[1,1,2,2]:  4!2! 2!=6\frac{n!}{c_1!\,c_2!\cdots c_m!}, \qquad [1, 1, 2]:\; \frac{3!}{2!\,1!} = 3, \qquad [1, 1, 2, 2]:\; \frac{4!}{2!\,2!} = 6
cvc_v is how many times value vv appears. Each distinct arrangement was counted c1!⋯cm!c_1! \cdots c_m! times by n!n!, once for every way of shuffling equal values among themselves.

Deep dive

Why "left twin unused" means "same level"

The check on sorted [1, 1, 2], index 1 (the second 1)

Whereused[0]What it meansDecision
Root, path []FalseThe first 1 was tried here and already unlockedSkip
Under [1]TrueThe first 1 sits one level upAllowed: builds [1, 1, ...]
Under [2]FalseThe first 1 was tried at this levelSkip
Under [2, 1]TrueThe first 1 is in the pathAllowed: builds [2, 1, 1]
If the left twin is unused, we are back at the level where it was just explored, so starting with this twin repeats that whole subtree.

Pattern 3

Next permutation: the array view

From one arrangement to the next, in place
  1. 1Diprightmost i with nums[i] < nums[i+1]
  2. 2Swapwith the smallest bigger value to its right
  3. 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].

Python
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]
O(n) time, O(1) space. If there is no dip the array is the last arrangement, and reversing it all wraps to the first.
Edit and run it in your browser

Every arrangement of [1, 2, 3] by repeated calls

BeforeDipSwap withAfter
[1, 2, 3]23[1, 3, 2]
[1, 3, 2]12[2, 1, 3]
[2, 1, 3]13[2, 3, 1]
[2, 3, 1]23[3, 1, 2]
[3, 1, 2]12[3, 2, 1]
[3, 2, 1]none-[1, 2, 3] (wrap)
Starting from sorted and calling n!−1n! - 1 times lists every permutation in lexicographic order with no recursion and O(1)O(1) extra space.

Family

Subsets, combinations, permutations

ProblemLoopSave whenCountPage
Subsetsrange(start, n), recurse i + 1Every node2n2^nSubsets
Combinations of size kkrange(start, n), recurse i + 1len(path) == k(nk)\binom{n}{k}Combinations
Permutationsrange(0, n) with usedlen(path) == nn!n!this page
Arrangements of size kkrange(0, n) with usedlen(path) == kn!(n−k)!\frac{n!}{(n-k)!}this page, stop early
Permutations IIrange(0, n), used, twin skiplen(path) == nn!∏cv!\frac{n!}{\prod c_v!}this page
In subsets [1,2]=[2,1][1, 2] = [2, 1], so the loop only looks forward. In permutations [1,2,3]≠[3,2,1][1, 2, 3] \neq [3, 2, 1], so it looks everywhere and the used array prevents reuse.

When only the k-th arrangement is wanted, skip the enumeration: each block of (n−1)!(n-1)! arrangements shares a first value, so dividing k−1k - 1 by (n−1)!(n-1)! picks it, and the remainder picks the rest. This is the factorial number system.

The k-th permutation from factorial digits

k−1=dn−1 (n−1)!+dn−2 (n−2)!+⋯+d1 1!,0≤di≤ik - 1 = d_{n-1}\,(n-1)! + d_{n-2}\,(n-2)! + \cdots + d_1\,1!, \qquad 0 \le d_i \le i
Digit did_i says which of the values still unused goes next. For n=4n = 4, k=9k = 9: 8=1⋅3!+1⋅2!+0⋅1!8 = 1 \cdot 3! + 1 \cdot 2! + 0 \cdot 1!, so take the 2nd, then the 2nd, then the 1st of what remains: 2, 3, 1, 4.
Python
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))            # 321
O(n²) with list removal; no enumeration at all.
Edit and run it in your browser

Choosing

Which version to write

Pick a pattern

Enumerate only when every arrangement is really needed. Counting, next and k-th questions all have answers far cheaper than n!.

Enumerate permutations when

  • The problem asks for all orderings, schedules or arrangements.
  • nn 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: n!n! 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.
  • nn is large: even n=13n = 13 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.

Sources