← Whiteboard questions

Permutations

List every ordering of a set of numbers

DSA, Medium, Backtracking

Which structure or algorithm, and what does it cost.

A list nums holds distinct whole numbers. Return every ordering of its numbers. Each ordering is a list that uses every number exactly once. List the orderings in any order. A list with one number has exactly one ordering.

Examples

Input nums = [4, 9, 2]
Output [[4, 9, 2], [4, 2, 9], [9, 4, 2], [9, 2, 4], [2, 4, 9], [2, 9, 4]]
Why three numbers give 3 * 2 * 1 = 6 orderings.
Input nums = [7]
Output [[7]]
Why one number has only one ordering.
Input nums = [-1, 5]
Output [[-1, 5], [5, -1]]
Why two numbers give 2 orderings: each can come first.

Constraints

Your answer must contain

Target Aim for O(n * n!) time, because the answer has n! orderings of n numbers each.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Fill the positions of the ordering one at a time. For the first position, which numbers can go there?

Hint 2 the approach

After you fill a position, the rest is the same question with one number fewer. You need a way to know which numbers are placed.

Hint 3 the key step

Keep the ordering so far in a list, and a used mark for each number. Skip used numbers, place one, recurse, then undo. Record a copy when full.

Walkthrough

Full walkthrough brute force to best

Brute force

Make every list of n positions where each position takes any of the n numbers, which is n^n lists. Keep a list only if no number repeats. For n = 8 that is 16,777,216 lists to look at, and only 40,320 of them are orderings. Each check costs O(n).

Best method

Build an ordering position by position. Keep the numbers placed so far in a list and a used mark for every number. On each call, if the list is full, record a copy. Otherwise loop over all the numbers. Skip a used number. Mark one, add it, call again, then remove it and unmark it. Each full list comes from a different sequence of choices, so each ordering is recorded once. Only unused numbers are tried, so no branch is wasted. The work is still n! lists, because the answer has that many.

Hand trace

Run on [4, 9, 2]. Place 4, then 9, then 2 and record [4, 9, 2]. Undo 2 and 9. Place 2, then 9 and record [4, 2, 9]. Undo back to the empty list. Place 9: then 4 and 2 give [9, 4, 2], and then 2 and 4 give [9, 2, 4]. Undo. Place 2: then 4 and 9 give [2, 4, 9], and then 9 and 4 give [2, 9, 4]. Six orderings.

Code

def permutations(nums):
    out = []
    path = []
    used = [False] * len(nums)
    def go():
        if len(path) == len(nums):
            out.append(path[:])
            return
        for i in range(len(nums)):
            if not used[i]:
                used[i] = True
                path.append(nums[i])
                go()
                path.pop()
                used[i] = False
    go()
    return out

Time and memory

O(n * n!) time: the call tree has at most e * n! calls (e is about 2.72), and each call loops over n numbers. Extra memory is O(n) for the list, the marks and the recursion, not counting the answer.

Common mistakes

  • Recording the list itself, not a copy. The later undo steps empty it, so every record ends up empty.
  • Forgetting to unmark a number when the call returns. Later orderings then miss that number.
  • Looping from a start position as in subsets. An ordering needs every unused number at every position.

Related problems

More Backtracking problems
Permutations: hints, walkthrough and Python solution