Lesson 23 · Core algorithms

Generating Permutations

A permutation is one ordering of all the items. To list every ordering, fill the positions one at a time: any unused item can go in the next position, and after trying it you take it back out and try the next. That gives n! orderings for n distinct items, built from a short recursive function.

Generating Permutations concept diagramBuilding the permutation c a d b of the letters a, b, c, d. Slot 1 can take any of 4 letters and takes c. Slot 2 has 3 left and takes a. Slot 3 has 2 left and takes d. Slot 4 has only b. The choices multiply to 4 × 3 × 2 × 1 = 24 = 4!. A bar chart below shows n! for n = 4, 6, 8, 10 and 12 on a log scale: 24, 720, 40,320, 3,628,800 and 479,001,600.one permutation of a b c d, slot by slotabcdcslot 14 choices×abcdaslot 23 choices×abcddslot 32 choices×abcdbslot 41 choice4 × 3 × 2 × 1 = 24 = 4!n! (log scale)n = 424n = 6720n = 840,320n = 103,628,800n = 12479,001,600
1

One Position at a Time

A permutation of n items uses each of them exactly once, in some order. The three items 1, 2, 3 have six: 123, 132, 213, 231, 312, 321. Counting is easy, as the combinatorics lesson shows: n choices for the first position, n − 1 for the second, and so on, giving n! in total. Listing them is the harder job.

To generate all permutations, build each one from left to right. The first position can hold any item. Once it is chosen, the second position can hold any item except that one, and so on until no item is left. Every complete row of choices is one permutation, and every permutation is reached by exactly one row of choices.

Drawn as a tree, the root has n children, each of those has n − 1, and the leaves at depth n are the answers. The search walks this tree depth first, so it only ever holds one partial permutation in memory.

  • Depth of the tree = n positions
  • Branching shrinks by one per level: n, n − 1, …, 1
  • Leaves = n! complete permutations
2

Permutations Using Recursion

  1. If the path holds all n items, save a copy and return
  2. Loop over every index i of the input
  3. Skip i if used[i] is set
  4. Set used[i], append the item, and recurse
  5. Pop the item and clear used[i]

Writing permutations with recursion needs only a path list and a boolean array of used flags. Each call fills one position. The loop offers every item, the flag rejects items already in the path, and the undo after the call makes the item available to later positions. This is the choose, explore, unchoose pattern from backtracking foundations.

On [1, 2, 3] the function makes 16 calls: one at the root, 3 at depth 1, 6 at depth 2 and 6 at the leaves. Because the loop tries items in input order, sorted input gives the permutations in sorted (lexicographic) order.

The same function lists the permutations of a string: split it into characters, permute the list, and join each result. "abc" gives abc, acb, bac, bca, cab, cba.

  • Flags make the "is it used?" check O(1); searching the path would cost O(n)
  • Save a copy of the path at a leaf, never the path itself
  • Clearing the flag is as important as popping the item
3

Cost: Why n! Is the Limit

There are n! leaves and each costs O(n) to copy, so listing every permutation takes O(n · n!) time. The internal nodes add only a constant factor. Extra space is O(n) for the path, flags and recursion stack, plus the output itself, which holds n! lists of length n.

n! grows faster than any power of 2. Eight items give 40,320 permutations, ten give 3,628,800, and thirteen give over six billion. If a problem needs every ordering, n is small. If n is large, the problem wants something else: a count from a formula, the next permutation only, or a search that prunes most branches.

  • Time O(n · n!), extra space O(n) besides the output
  • n ≤ 8 is quick, n = 10 takes seconds, n ≥ 12 is usually too slow
  • Counting does not need listing: the answer is n!
Key reference

Terms, operations, and practical uses

Key terms

  • PermutationOne ordering of all n items; there are n! of them when the items are distinct.
  • Used flagA boolean per item marking that it is already in the current path.
  • Lexicographic orderDictionary order: compare first positions, then second, and so on.
  • Heap's algorithmLists every permutation with one swap between consecutive ones.
Implementation

Code in Python, C++ and Java

def permutations(items):
    result, path, used = [], [], [False] * len(items)
    calls = 0

    def build():
        nonlocal calls
        calls += 1
        if len(path) == len(items):
            result.append(path[:])
            return
        for i, item in enumerate(items):
            if used[i]:
                continue
            used[i] = True
            path.append(item)
            build()
            path.pop()
            used[i] = False

    build()
    return result, calls


def unique_permutations(items):
    items = sorted(items)
    result, path, used = [], [], [False] * len(items)

    def build():
        if len(path) == len(items):
            result.append(path[:])
            return
        for i, item in enumerate(items):
            if used[i] or (i > 0 and items[i] == items[i - 1] and not used[i - 1]):
                continue
            used[i] = True
            path.append(item)
            build()
            path.pop()
            used[i] = False

    build()
    return result


def heaps_order(items):
    a, c, out = list(items), [0] * len(items), [list(items)]
    i = 1
    while i < len(a):
        if c[i] < i:
            j = 0 if i % 2 == 0 else c[i]
            a[j], a[i] = a[i], a[j]
            out.append(a[:])
            c[i] += 1
            i = 1
        else:
            c[i] = 0
            i += 1
    return out


def text(perms):
    return " ".join("".join(map(str, p)) for p in perms)


perms, calls = permutations([1, 2, 3])
print("permutations of 1 2 3:", text(perms), f"({len(perms)} results, {calls} calls)")
print("permutations of abc:", text(permutations(list("abc"))[0]))
print("plain method on 1 1 2:", text(permutations([1, 1, 2])[0]))
print("with the skip rule:", text(unique_permutations([1, 1, 2])))
print("Heap's algorithm order:", text(heaps_order([1, 2, 3])))
print("count for n = 4:", len(permutations([1, 2, 3, 4])[0]))
print("n = 0:", permutations([])[0])
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

template <class T>
struct Permuter {
    vector<T> items;
    vector<vector<T>> result;
    vector<T> path;
    vector<bool> used;
    bool skipDuplicates;
    int calls = 0;

    Permuter(vector<T> v, bool skip) : items(v), used(v.size(), false), skipDuplicates(skip) {
        if (skip) sort(items.begin(), items.end());
        build();
    }

    void build() {
        calls++;
        if (path.size() == items.size()) {
            result.push_back(path);
            return;
        }
        for (size_t i = 0; i < items.size(); i++) {
            if (used[i]) continue;
            if (skipDuplicates && i > 0 && items[i] == items[i - 1] && !used[i - 1]) continue;
            used[i] = true;
            path.push_back(items[i]);
            build();
            path.pop_back();
            used[i] = false;
        }
    }
};

vector<vector<int>> heapsOrder(vector<int> a) {
    vector<int> c(a.size(), 0);
    vector<vector<int>> out = {a};
    size_t i = 1;
    while (i < a.size()) {
        if (c[i] < (int)i) {
            size_t j = i % 2 == 0 ? 0 : c[i];
            swap(a[j], a[i]);
            out.push_back(a);
            c[i]++;
            i = 1;
        } else {
            c[i] = 0;
            i++;
        }
    }
    return out;
}

template <class T>
string text(const vector<vector<T>>& perms) {
    string s;
    for (size_t k = 0; k < perms.size(); k++) {
        if (k) s += " ";
        for (const T& x : perms[k]) {
            if constexpr (is_same_v<T, char>) s += x;
            else s += to_string(x);
        }
    }
    return s;
}

int main() {
    Permuter<int> p({1, 2, 3}, false);
    cout << "permutations of 1 2 3: " << text(p.result) << " (" << p.result.size() << " results, " << p.calls << " calls)\n";
    cout << "permutations of abc: " << text(Permuter<char>({'a', 'b', 'c'}, false).result) << "\n";
    cout << "plain method on 1 1 2: " << text(Permuter<int>({1, 1, 2}, false).result) << "\n";
    cout << "with the skip rule: " << text(Permuter<int>({1, 1, 2}, true).result) << "\n";
    cout << "Heap's algorithm order: " << text(heapsOrder({1, 2, 3})) << "\n";
    cout << "count for n = 4: " << Permuter<int>({1, 2, 3, 4}, false).result.size() << "\n";
    auto empty = Permuter<int>({}, false).result;
    cout << "n = 0: " << (empty.size() == 1 && empty[0].empty() ? "[[]]" : "none") << "\n";
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    static int calls;

    static <T extends Comparable<T>> List<List<T>> permutations(List<T> input, boolean skipDuplicates) {
        List<T> items = new ArrayList<>(input);
        if (skipDuplicates) items.sort(null);
        List<List<T>> result = new ArrayList<>();
        calls = 0;
        build(items, new ArrayList<>(), new boolean[items.size()], skipDuplicates, result);
        return result;
    }

    static <T> void build(List<T> items, List<T> path, boolean[] used, boolean skip, List<List<T>> result) {
        calls++;
        if (path.size() == items.size()) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < items.size(); i++) {
            if (used[i]) continue;
            if (skip && i > 0 && items.get(i).equals(items.get(i - 1)) && !used[i - 1]) continue;
            used[i] = true;
            path.add(items.get(i));
            build(items, path, used, skip, result);
            path.remove(path.size() - 1);
            used[i] = false;
        }
    }

    static List<List<Integer>> heapsOrder(List<Integer> input) {
        List<Integer> a = new ArrayList<>(input);
        int[] c = new int[a.size()];
        List<List<Integer>> out = new ArrayList<>();
        out.add(new ArrayList<>(a));
        int i = 1;
        while (i < a.size()) {
            if (c[i] < i) {
                int j = i % 2 == 0 ? 0 : c[i];
                Integer t = a.get(j); a.set(j, a.get(i)); a.set(i, t);
                out.add(new ArrayList<>(a));
                c[i]++;
                i = 1;
            } else {
                c[i] = 0;
                i++;
            }
        }
        return out;
    }

    static <T> String text(List<List<T>> perms) {
        StringBuilder sb = new StringBuilder();
        for (List<T> p : perms) {
            if (sb.length() > 0) sb.append(' ');
            for (T x : p) sb.append(x);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        List<List<Integer>> perms = permutations(List.of(1, 2, 3), false);
        System.out.println("permutations of 1 2 3: " + text(perms) + " (" + perms.size() + " results, " + calls + " calls)");
        System.out.println("permutations of abc: " + text(permutations(Arrays.asList('a', 'b', 'c'), false)));
        System.out.println("plain method on 1 1 2: " + text(permutations(List.of(1, 1, 2), false)));
        System.out.println("with the skip rule: " + text(permutations(List.of(1, 1, 2), true)));
        System.out.println("Heap's algorithm order: " + text(heapsOrder(List.of(1, 2, 3))));
        System.out.println("count for n = 4: " + permutations(List.of(1, 2, 3, 4), false).size());
        System.out.println("n = 0: " + permutations(new ArrayList<Integer>(), false));
    }
}
Watch it run

Step through it

Running on [1, 2, 3]

permutations of 1 2 3 · each level fills one slot with an unused value·slot 1slot 2slot 3used123nothing used yetcalls 1 · results 0
Step 1

Three empty slots

A permutation fills n slots, using every value exactly once. The search starts at the root with all three values free. The first slot can take any of them, so the root will get three children.

Output
1 / 14
4

Repeated Values

If the input has repeats, the plain method treats equal values as different and prints duplicates. [1, 1, 2] has only three distinct orderings, 112, 121, 211, but the function prints six results, each twice.

The fix keeps equal values in a fixed relative order. Sort the input so equal values sit side by side. In the loop, skip index i when items[i] equals items[i − 1] and used[i − 1] is not set. That rule means the second copy can only be placed after the first copy is already in the path, so each distinct ordering is built exactly once. With m₁, m₂, … copies of each value, the count drops to n! / (m₁! · m₂! · …).

A set of finished results also removes duplicates, but only after building all n! of them. The skip rule never enters the duplicate branches.

  • Sort first; the skip rule relies on equal values being adjacent
  • Skip when the previous equal copy is not in use
  • Count of distinct orderings: n! divided by the factorial of each value's count
5

Swaps and Heap's Algorithm

Permutations can also be built in place, with no path and no flags. The swap method fixes position k by swapping each later item into it, recursing on position k + 1, and swapping back. It uses O(1) extra space besides the stack, but its output is not in sorted order.

Heap's algorithm, published by B. R. Heap in 1963, goes further: each permutation differs from the previous one by a single swap. For 1 2 3 the order is 123, 213, 312, 132, 231, 321. That makes it the fastest way to visit every ordering when the order itself does not matter, such as trying every route through a few stops.

When the order does matter, the next permutation in sorted order can be found from the current one in O(n), without recursion. That step is its own problem: Next Permutation.

Three ways to list the permutations of n items
MethodExtra memoryOutput orderRepeats handled?
Used flags and a pathO(n)Sorted, if the input is sortedYes, with the skip rule
Swap in placeO(n) stackNot sortedNeeds a set per position
Heap's algorithmO(n) countersNot sorted; one swap apartNo
  • Need sorted output or repeats removed: flags and the skip rule
  • Need speed and any order: Heap's algorithm
  • Need only the next one: next permutation in O(n)
6

Practice and Next Steps

Start with the plain problem, then add repeats, then the variants that skip listing altogether. Choosing a subset instead of an ordering is covered in subsets and combinations.