Skip to main content
Medium Backtracking High frequency

Permutations

Open on LeetCode

Approach Summary

Swap elements to place each number at index 0 recursively, or use a used[] array and add unused elements at each step.

Full Solution & Approach

Generate permutations by deciding, at each position, which unused element goes there. Use a visited boolean array to track which elements are already in the current path. The recursive helper appends an unused element, recurses, then removes it — the choose/explore/unchoose skeleton. When the path length equals the array length, record a copy. Since all elements are distinct, the visited-array guard is sufficient and no duplicate handling is needed. The recursion tree has n! leaves — every permutation appears exactly once. An alternative swaps elements in place (no extra array) but is slightly harder to reason about; the visited-array version is the clearest. The same skeleton with different guards produces combinations and subsets.

There are n! permutations, each costing O(n) to build and copy — O(n × n!) time. The recursion depth is n and the path holds n elements — O(n) space.

Solution Code

Solution

def permute(nums: list[int]) -> list[list[int]]:
    res = []
    used = [False] * len(nums)

    def backtrack(path: list[int]) -> None:
        if len(path) == len(nums):
            res.append(path[:])
            return
        for i, n in enumerate(nums):
            if not used[i]:
                used[i] = True
                path.append(n)
                backtrack(path)
                path.pop()
                used[i] = False

    backtrack([])
    return res

Edge Cases to Watch

  • Empty array — return [[]]
  • Single element — one permutation
  • Repeated values — not in this problem; Permutations II adds a sort-and-skip guard

How to Recognize This Pattern

  • Generate all permutations
  • No duplicate numbers

Complexity Analysis

Time Complexity

O(n × n!)

Space Complexity

O(n)

Tags

Array Backtracking

This site is free. If these guides are helping your prep, consider buying me a coffee. ☕

Support →
Buy me a coffee