Permutations - Backtracking Pattern

Permutations in Java using the Backtracking pattern: problem statement, approach, template, complexity, and interview tips.

Permutations

Problem Statement

Return all permutations of an array of distinct integers.

Pattern: Backtracking

Build a solution step by step, undo the last choice when it leads nowhere, and prune invalid branches early.

Use this pattern when the task asks for all permutations, subsets, combinations or placements that satisfy constraints.

Approach

  1. Define the state (current path) and the condition for a complete solution.
  2. Loop over the available choices, make a choice and recurse.
  3. Undo the choice after the recursive call returns.

Pattern Template (Java)

void backtrack(List<Integer> path, int start) {
    if (/* path is a complete solution */) {
        result.add(new ArrayList<>(path));
        return;
    }
    for (int i = start; i < nums.length; i++) {
        path.add(nums[i]);
        backtrack(path, i + 1);
        path.remove(path.size() - 1);
    }
}

Adapt this template to the exact rules of Permutations: decide what state you track, what condition moves the loop forward, and what the final answer is.

Complexity

Exponential in general (for example O(n!) or O(2^n)); pruning reduces the work in practice.

Interview Tips

  • Always copy the path before storing it.
  • Sort the input and skip equal neighbours when duplicates must not repeat.
  • Start with a brute-force idea, state its complexity, then explain how the Backtracking pattern improves it.
  • Walk through a small example and at least one edge case (empty input, a single element, duplicates).

Continue Learning

Parent: DSA Interview Learning Path | Next: Subsets

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.