CodeArchon

mediumBacktrackingMicrosoftLinkedInAmazon

Lineup Shuffler

A scheduling coach enumerates every ordering of a roster for alternate practice lineups.

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

Choose approach

1
0
i
2
1
3
2
SetPermutations (0)
empty
1/22
Narrationstep 1 of 22

Begin DFS; try every unused element at each depth.

1def permute(nums):
2 out, used, cur = [], [False]*len(nums), []
3 def dfs():
4 if len(cur) == len(nums):
5 out.append(cur[:]); return
6 for i in range(len(nums)):
7 if used[i]: continue
8 used[i] = True; cur.append(nums[i])
9 dfs()
10 cur.pop(); used[i] = False
11 dfs(); return out
Variables
cur=[]
out=0

How to think about it

  1. n! leaves — unavoidable.
  2. `used` flag array prevents reuse at a given depth.
  3. Backtrack: pop and unflag after recursion returns.

Edge cases to catch in interview

  • n = 0 -> single empty permutation.
  • Duplicates NOT in input (that's a different problem).

Examples

Example 16 orderings
{"values":[1,2,3]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed