Hard: Advanced Interview · Problem 68 of 82

All Permutations

HardFunctionsPython

Write permutations(items) that returns a list of all the orderings of the items, each as a list. The items are all different.

The orderings must come in this order: choose the first item left to right, and for each choice order the rest the same way. So permutations([1, 2, 3]) is [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]].

Understand the problem

Count and find the base case.

How many orderings do 4 different items have?

There are 4 choices for the first place, 3 for the second, 2 for the third and 1 for the last: 4 x 3 x 2 x 1 = 24. This is the factorial, written 4!. It grows very fast: 10 items have 3,628,800 orderings.

What should permutations([]) return?

  1. [], there are no orderings
  2. [[]], one ordering: the empty one
  3. An error

There is exactly one way to arrange nothing: the empty arrangement. This is the base case of the recursion, and it makes the recursive step work without special cases. [] (no orderings at all) would make every answer empty.

Write the solution

Return a list of lists, in the order given in the task.

def permutations(items):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

If you pick one item to go first, what remains to be solved?

Hint 2: the shape of the answer

For each position i, take items[i] as the first item and recurse on the list without it (items[:i] + items[i + 1:]). Put the chosen item in front of each ordering that comes back.

Hint 3: pseudocode

if items is empty: return [[]] result = [] for i, first in enumerate(items): rest = items without position i for ordering in permutations(rest): result.append([first] + ordering) return result

Reflect

Solution: recursion

def permutations(items):
    if not items:
        return [[]]
    result = []
    for i, first in enumerate(items):
        rest = items[:i] + items[i + 1:]
        for ordering in permutations(rest):
            result.append([first] + ordering)
    return result

Another way: itertools

from itertools import permutations as _permutations

def permutations(items):
    return [list(p) for p in _permutations(items)]

What this tests: recursion with a loop inside, list slicing and concatenation, and the base case of an empty input.

How to think about it: "choose the first item, then solve the smaller problem". The base case is one arrangement for nothing, [[]]. This pattern ("choose, recurse, combine") is called backtracking when you also undo choices; here the slicing creates a fresh list each time, so there is nothing to undo.

Cost: there are n! orderings, so any solution is at least O(n!) in time and output size. That is why this is only used for small n.

itertools.permutations gives the same order and returns tuples. Know it, but be ready to write the recursion.

What an interviewer might ask next: Generate the permutations of a list that contains repeated items, without duplicate orderings. (Sort the items and skip a choice equal to the previous one at the same level.)