Skip to lesson

Generating permutations

In a subset, [1, 2, 3] and [3, 2, 1] are the same selection; in a permutation, order matters, so every rearrangement of all n elements is a distinct answer. An array of n distinct elements has n! = n × (n - 1) × … × 1 permutations, and backtracking gives you two classic ways to generate them.

Using a used[] array

A permutation is one ordering of all the elements. n different elements have n! permutations.

When we generated subsets, we passed a start index and only looked forward (i = start .. n - 1) so we would never pick an earlier element out of order.

  1. Goal: When current.size() == nums.length, all n elements have been placed. Add new ArrayList<>(current) to results and return.
  2. Loop: For int i = 0; i < nums.length; i++, if used[i] is true, continue.
  3. Choose: Set used[i] = true and current.add(nums[i]).
  4. Explore: Call backtrack(nums, used, current, results).
  5. Un-choose: Remove the last element from current and set used[i] = false.

Permutation State Tree for nums = [1, 2] Using used[]

Step 1 of 4

[][1]pick i=0[2]skip 1[1,2][2,1]skip 2
i
0
choice
1
used[]
  1. T
  2. F
current
  1. 1
At root [], pick i = 0 (nums[0] = 1): mark used[0] = true and add 1 to current.

Example 1 · Brute force: try every index sequence, keep the distinct ones (O(n^n · n) time, O(1) space)

PermutationsBrute.javaJava
public class PermutationsBrute {    public static void main(String[] args) {        int n = 4;        int total = 1;        for (int i = 0; i < n; i++) total *= n;        int valid = 0;        for (int code = 0; code < total; code++) {            boolean[] seen = new boolean[n];            boolean distinct = true;            int rest = code;            for (int pos = 0; pos < n; pos++) {                int digit = rest % n;                rest /= n;                if (seen[digit]) {                    distinct = false;                    break;                }                seen[digit] = true;            }            if (distinct) valid++;        }        System.out.println("Sequences checked: " + total);        System.out.println("Valid permutations: " + valid);    }}
Output
Sequences checked: 256
Valid permutations: 24

What this code does

  • For n = 4 it checks all 4⁴ = 256 index sequences and keeps the 24 that repeat no index.
  • It is slow because it builds sequences that repeat an index and rejects them only at the end.

Example 2 · Optimal: extend only with unused numbers using used[] (O(n · n!) time, O(n) space)

PermutationsUsedArray.javaJava
import java.util.ArrayList;import java.util.List;
public class PermutationsUsedArray {    public static List<List<Integer>> permute(int[] nums) {        List<List<Integer>> results = new ArrayList<>();        boolean[] used = new boolean[nums.length];        backtrack(nums, used, new ArrayList<>(), results);        return results;    }
    private static void backtrack(int[] nums, boolean[] used, List<Integer> current, List<List<Integer>> results) {        if (current.size() == nums.length) {            results.add(new ArrayList<>(current));            return;        }        for (int i = 0; i < nums.length; i++) {            if (used[i]) continue;            used[i] = true;                       // 1. Choose            current.add(nums[i]);            backtrack(nums, used, current, results); // 2. Explore            current.remove(current.size() - 1);   // 3. Un-choose            used[i] = false;        }    }
    public static void main(String[] args) {        List<List<Integer>> perms = permute(new int[]{1, 2, 3});        System.out.println("Count: " + perms.size());        System.out.println(perms);    }}
Output
Count: 6
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

What this code does

  • At depth 0 we have 3 choices (1, 2, 3); at depth 1 we have 2 unused choices; at depth 2 we have 1 unused choice, producing 3 × 2 × 1 = 6 leaves.
  • Notice that used[i] = false is paired with current.remove(current.size() - 1) so both pieces of state stay in sync.
  • used[] stops a branch the moment a number would repeat, so only the n! valid permutations are ever built (6 here, 24 for n = 4).

In a permutation, however, picking nums[2] first still requires us to go back and pick nums[0] and nums[1] for the later slots! That means every recursive call loops i from 0 to nums.length - 1. To avoid picking the same index twice in one permutation, we keep a boolean[] used array of length n. Before choosing nums[i], we check if (used[i]) continue;: if index i is already inside current, we skip it.

The swap method

Can we generate all permutations without allocating a boolean[] used array or even a separate current list during the search? Yes—by swapping elements in place inside nums itself.

Example 3 · Permutations by In-Place Swapping

PermutationsSwap.javaJava
import java.util.ArrayList;import java.util.List;
public class PermutationsSwap {    public static List<List<Integer>> permuteSwap(int[] nums) {        List<List<Integer>> results = new ArrayList<>();        backtrack(nums, 0, results);        return results;    }
    private static void backtrack(int[] nums, int idx, List<List<Integer>> results) {        if (idx == nums.length) {            List<Integer> snapshot = new ArrayList<>(nums.length);            for (int x : nums) snapshot.add(x);            results.add(snapshot);            return;        }        for (int i = idx; i < nums.length; i++) {            swap(nums, idx, i);              // 1. Choose nums[i] for slot idx            backtrack(nums, idx + 1, results); // 2. Explore remaining slots            swap(nums, idx, i);              // 3. Un-choose (swap back)        }    }
    private static void swap(int[] a, int i, int j) {        int temp = a[i];        a[i] = a[j];        a[j] = temp;    }
    public static void main(String[] args) {        System.out.println(permuteSwap(new int[]{1, 2, 3}));    }}
Output
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]

What this code does

  • No boolean[] used or shared List<Integer> current is needed: the subarray nums[0 .. idx - 1] is the chosen prefix and nums[idx .. n - 1] holds the remaining candidates.
  • Swapping nums[idx] and nums[i] a second time after the recursive call restores nums to its exact order before the choice.

At recursion depth idx, indices 0 .. idx - 1 already hold the fixed prefix of our permutation, and indices idx .. n - 1 hold the remaining unused candidates. We loop i from idx to n - 1: swap nums[idx] with nums[i] (choosing nums[i] for slot idx), recurse to idx + 1, and then swap nums[idx] and nums[i] back to restore the array. At the base case (idx == nums.length), we copy the current nums array into a List<Integer>.

The used[] method preserves lexicographical order when nums is sorted, whereas the in-place swap method does not (for [1, 2, 3], swapping index 0 and 2 turns [1, 2, 3] into [3, 2, 1], so [3, 2, 1] appears before [3, 1, 2]). Both run in O(n · n!) time and O(n) auxiliary space.

Permutations with duplicates

Suppose nums = [1, 1, 2]. There are two identical 1s at index 0 and index 1.

Example 4 · Permutations II: Handling Duplicates with !used[i - 1]

PermutationsWithDuplicates.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class PermutationsWithDuplicates {    public static List<List<Integer>> permuteUnique(int[] nums) {        Arrays.sort(nums); // Group equal elements together        List<List<Integer>> results = new ArrayList<>();        boolean[] used = new boolean[nums.length];        backtrack(nums, used, new ArrayList<>(), results);        return results;    }
    private static void backtrack(int[] nums, boolean[] used, List<Integer> current, List<List<Integer>> results) {        if (current.size() == nums.length) {            results.add(new ArrayList<>(current));            return;        }        for (int i = 0; i < nums.length; i++) {            if (used[i]) continue;            // Skip duplicate at the same decision level:            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {                continue;            }            used[i] = true;            current.add(nums[i]);            backtrack(nums, used, current, results);            current.remove(current.size() - 1);            used[i] = false;        }    }
    public static void main(String[] args) {        System.out.println("Unique permutations of [1, 2, 1]: " + permuteUnique(new int[]{1, 2, 1}));        System.out.println("Unique permutations of [2, 2, 1, 1]: " + permuteUnique(new int[]{2, 2, 1, 1}));    }}
Output
Unique permutations of [1, 2, 1]: [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
Unique permutations of [2, 2, 1, 1]: [[1, 1, 2, 2], [1, 2, 1, 2], [1, 2, 2, 1], [2, 1, 1, 2], [2, 1, 2, 1], [2, 2, 1, 1]]

What this code does

  • For [1, 2, 1], sorting yields [1, 1, 2]. At depth 0, i = 0 picks the first 1. When that branch finishes and backtracks (used[0] becomes false), the loop reaches i = 1. Since nums[1] == nums[0] and !used[0] is true, i = 1 is skipped at depth 0.
  • Inside the branch where used[0] is true (depth 1), !used[0] is false, so i = 1 is allowed to be picked as the second 1 in [1, 1, 2].

If we run the plain used[] algorithm, we get [1, 1, 2] twice: once with (index 0, index 1, index 2) and once with (index 1, index 0, index 2). To eliminate duplicate permutations, first sort nums so equal numbers are adjacent. Then enforce a single rule: among identical numbers, you may only pick nums[i] if its left neighbor nums[i - 1] has already been used in the current prefix. In code, inside the for (int i = 0; i < nums.length; i++) loop, skip index i when:

  • if (used[i]) continue; — index i is already in the current permutation.
  • if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue; — nums[i] equals nums[i - 1], and nums[i - 1] is not currently in use (!used[i - 1]), meaning we just finished exploring nums[i - 1] in this exact slot and backtracked. Forcing identical items to be picked in index order (0 before 1) ensures [1, 1, 2] is generated only once.

Find the bug

Spot the backtracking bug

Each snippet has one wrong line. Tap the line to fix, then check.

Some permutations come out with extra numbers.

Round 1 of 3

Next step

Check your understanding

10 quick questions