BackendML

Permutations

Medium2 min read
The Permutations problem requires finding all possible arrangements of the elements in an array, where the order of elements matters.

Problem

Given an array of distinct integers nums, return all possible permutations of the elements.

Each element must be used exactly once in every permutation, and different orders are considered different permutations.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

nums = [1,2,3]

Output

[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Solution

This solution uses Backtracking to generate all possible permutations. At each step, an unused number is added to the current permutation, and the recursion continues until all numbers have been selected.

A visited array keeps track of which elements have already been used in the current permutation. This prevents the same element from being selected more than once.

When the current permutation contains all n elements, it is added to the result.

After each recursive call, the selected element is removed and marked as unused so that it can be used in another position.
public List<List<Integer>> permute(int[] nums) {
    List<List<Integer>> result = new ArrayList<>();
    boolean[] visited = new boolean[nums.length];

    backtrack(nums, new ArrayList<>(), result, visited);
    return result;
}

private void backtrack(int[] nums, List<Integer> current,
        List<List<Integer>> result, boolean[] visited) {

    // A complete permutation is found.
    if (current.size() == nums.length) {
        result.add(new ArrayList<>(current));
        return;
    }

    for (int i = 0; i < nums.length; i++) {
        // Skip the element if it is already used.
        if (visited[i]) {
            continue;
        }

        // Choose the current element.
        current.add(nums[i]);
        visited[i] = true;

        // Continue building the permutation.
        backtrack(nums, current, result, visited);

        // Undo the choice.
        visited[i] = false;
        current.remove(current.size() - 1);
    }
}

Complexity

There are n! possible permutations, and each permutation contains n elements. Therefore, the time complexity is O(n × n!).

The recursion depth is O(n), and the visited array requires O(n) space, excluding the space required for the output.

Comments

No comments yet. Ask a question or share what helped.