Skip to content

Permutations

MediumLeetCode #46Time O(n · n!)Space O(n)

You get an array of distinct integers. Return every way to arrange all of them. Any order of the answers is fine.

nums = [1, 2, 3] -> [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]

Here order matters, so [1, 2] and [2, 1] are both wanted. That means no start index. At every level, any number you haven’t used yet may go next.

Track what’s on the path with a used array. Each level loops over all indices, skips the used ones, and does the usual choose, explore, un-choose. This time un-choosing has two parts: pop the path and reset used[i]. A path is finished when its length equals n.

The tree has n choices at the top, n-1 next, and so on: n! leaves.

Show solutionHide solution
def permute(nums: list[int]) -> list[list[int]]:
res, path = [], []
used = [False] * len(nums)
def backtrack() -> None:
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)): # every unused number can go next
if used[i]:
continue
used[i] = True
path.append(nums[i]) # choose
backtrack() # explore
path.pop() # un-choose
used[i] = False
backtrack()
return res
  • Time: O(n · n!) — there are n! permutations, and copying each into the result costs O(n). The loops at inner nodes add only a constant factor on top of that.
  • Space: O(n) — the path, the used array and the recursion are each at most n. The output is not counted.
  • Reset used[i] when you un-choose. Forgetting it means later branches think the number is still taken and you return too few answers.
  • Copy the path before adding it to the results.
  • Don’t reuse the subsets template. A start index would only produce increasing orders, so you’d get just one permutation.

The array may contain duplicates; return unique permutations. The trick: sort, then skip nums[i] if it equals nums[i - 1] and nums[i - 1] is not currently used. That forces equal numbers to be placed in left-to-right order.

Rearrange into the next larger ordering, in place. The trick: no backtracking. Find the rightmost ascent, swap its left value with the smallest larger value to its right, then reverse the tail.

Does one string contain a permutation of another as a substring? The trick: you don’t generate permutations at all. Slide a window and compare letter counts.