Recursion & Backtracking · Pattern 4 of 9

Permutations: every order of the items

Fill position by position with an item not used yet. Either swap candidates into place or keep a used array; for duplicates, sort and only use the first unused copy of each value.

3 variations · 3 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Every ordering or arrangement of the items
  • Each item must be used exactly once
  • Assign distinct values (digits, seats) to distinct things

The template

Permutations
// swap trick: positions 0..i-1 are fixed, try every item from i.. in position i
List<List<Integer>> permute(int[] a) {
    List<List<Integer>> out = new ArrayList<>();
    swapGo(a, 0, out);
    return out;
}
void swapGo(int[] a, int i, List<List<Integer>> out) {
    if (i == a.length) {
        List<Integer> p = new ArrayList<>();
        for (int x : a) p.add(x);
        out.add(p);
        return;
    }
    for (int j = i; j < a.length; j++) {
        swap(a, i, j);
        swapGo(a, i + 1, out);
        swap(a, i, j);                        // swap back
    }
}
void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }

// with duplicates: sort, and use a value only if its earlier copy is already in the path
List<List<Integer>> permuteUnique(int[] a) {
    Arrays.sort(a);
    List<List<Integer>> out = new ArrayList<>();
    usedGo(a, new boolean[a.length], new ArrayList<>(), out);
    return out;
}
void usedGo(int[] a, boolean[] used, List<Integer> path, List<List<Integer>> out) {
    if (path.size() == a.length) { out.add(new ArrayList<>(path)); return; }
    for (int i = 0; i < a.length; i++) {
        if (used[i] || (i > 0 && a[i] == a[i - 1] && !used[i - 1])) continue;
        used[i] = true; path.add(a[i]);
        usedGo(a, used, path, out);
        path.remove(path.size() - 1); used[i] = false;
    }
}

The variations

  1. 1Every order of distinct items

    Position by position, try each item that is not used yet. A used array (or the swap trick) makes "not used yet" an O(1) check.

  2. 2Permutations with duplicates

    Sort, then treat equal values as a queue: a copy may be used only if the copy before it is already in the path. Each distinct order is then built once.

  3. 3Assign distinct values under a constraint

    Letters get distinct digits, which is a permutation of digits over letters. Fill column by column from the right, carry the sum, and prune a branch as soon as a column cannot balance.

Mistakes to avoid

  • Forgetting to swap back, so the array is scrambled for the next branch.
  • Using the swap trick with duplicates: swapping scrambles the sorted order, so the "skip equal neighbours" rule no longer works. Use the used array instead.
  • Starting the loop at a start index (as in subsets): permutations try every unused item at every position.
Next: Grid backtracking: paths and boards →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.