InterviewPrepKit

Home / Coding / Backtracking

Permutations

medium Original β†—
Solving tips
  • Archetypal backtracking: choose an unused element for each position, recurse, then undo; record a copy when the path reaches length n.
  • Track availability with a boolean used array, or generate in place by swapping nums[first] with each nums[i>=first] and swapping back.
  • Every choice must be exactly reversed on the way back up (pop / unmark / reverse swap) or sibling branches get corrupted.
  • Time is O(n * n!) with O(n) recursion depth; append path[:] (or nums[:]), never a live reference.

Problem

Given an array nums of distinct integers, return all possible permutations of its elements. A permutation is an arrangement that uses every element exactly once; two permutations differ if the elements appear in a different order.

You may return the permutations in any order, but each of the n! distinct orderings must appear exactly once.

Examples

  • Input: nums = [1, 2, 3] β†’ Output: [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]] All 3! = 6 orderings of three distinct numbers.
  • Input: nums = [0, 1] β†’ Output: [[0,1], [1,0]] The two orderings of a pair.
  • Input: nums = [7] β†’ Output: [[7]] A single element has exactly one permutation.

Constraints

  • 1 <= nums.length <= 6.
  • -10 <= nums[i] <= 10.
  • All integers in nums are distinct.

With n <= 6, the output has at most 6! = 720 permutations β€” small, but the enumeration itself is inherently factorial.

Think about it first

Hint 1 Build a permutation one position at a time. For the first slot you may place any element; for the next slot, any element not yet used; and so on. What do you need to remember to avoid reusing an element?
Hint 2 This is textbook backtracking: keep a partial arrangement and a way to know which elements are still available. Place one, recurse, then remove it (undo) and try the next available element.
Hint 3 Track availability with a boolean `used` array, or swap elements into place in the array itself. When the partial arrangement reaches length `n`, you have a complete permutation β€” record a copy of it.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.