Permutations

Return all possible permutations of a set of distinct integers.

Pattern

Swap/Used Array

This problem follows the Swap/Used Array pattern, commonly found in the Backtracking category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Fix each element at current position. Recurse for remaining. Track used elements.

Key Insight

Unlike subsets where order doesn't matter, permutations always start from index 0 — you skip already-used elements instead of incrementing the start index.

Step-by-step

  1. 1Use a 'used' boolean array to track which elements are in the current permutation
  2. 2At each recursive step, try each unused element
  3. 3Add it to the current permutation, mark as used, recurse
  4. 4Backtrack: remove it and mark as unused
  5. 5Base case: when current permutation length equals n, add to results

Pseudocode

result = []
def backtrack(current):
    if len(current) == len(nums):
        result.append(current[:])
        return
    for num in nums:
        if num in current: continue  # or use 'used' array
        current.append(num)
        backtrack(current)
        current.pop()
backtrack([])
return result
Complexity Analysis

Time Complexity

O(n * n!)

Space Complexity

O(n)
More Backtracking Problems

Master this pattern with YeetCode

Practice Permutations and similar Backtracking problems with flashcards. Build pattern recognition through active recall.

Practice this problem