AlgoViz

Permutations

medium 24 min

Generating 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

  1. 10
  2. 21
  3. 32

path

  1. _0
  2. _1
  3. _2
used = F F Ffound = 0 / 6path [] · need 3 more

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

  1. Alice
  2. Bob
  3. Cara

line

  1. _
  2. _
  3. _
3 choices for spot 1

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 photos

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Looping from start instead of 0

    critical

    A 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!.

    Wrong
    for i in range(start, len(nums)):   # combinations rule    path.append(nums[i])    backtrack(i + 1)    path.pop()
    Right
    for 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] = False
  • Popping the path but not unlocking used[i]

    critical

    The 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.

    Wrong
    used[i] = Truepath.append(nums[i])backtrack()path.pop()             # used[i] still True
    Right
    used[i] = Truepath.append(nums[i])backtrack()path.pop()used[i] = False        # undo both
  • Saving the path, not a copy

    critical

    path is one list that keeps changing. Appending it stores a reference, so after backtracking every saved answer is the same empty list.

    Wrong
    result.append(path)        # n! references to one list
    Right
    result.append(path[:])     # a snapshot
  • Permutations II without the used[i - 1] check

    major

    Skipping 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.

    Wrong
    if i > 0 and nums[i] == nums[i - 1]:    continue           # [1, 1, 2] returns []
    Right
    nums.sort()if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:    continue           # only repeats at this level
  • Forgetting to swap back

    major

    In 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.

    Wrong
    nums[start], nums[i] = nums[i], nums[start]backtrack(start + 1)   # array left scrambled
    Right
    nums[start], nums[i] = nums[i], nums[start]backtrack(start + 1)nums[start], nums[i] = nums[i], nums[start]   # restore
  • Next permutation with > instead of >=

    minor

    With 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].

    Wrong
    while i >= 0 and nums[i] > nums[i + 1]:    i -= 1...while nums[j] < nums[i]:    j -= 1
    Right
    while 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.