Recursion

O(k!)·O(k) space
permute([])chosen so far: 0/3
  • Running

Call permute([]).

Call permute([]).
  1. 1to build every arrangement of the values, one choice at a time
  2. 2if the prefix already contains every value, that arrangement is complete
  3. 3otherwise, for each value not already in the prefix, add it and continue with what remains
  4. 4once every arrangement that choice could lead to has been found, remove it again
  5. 5every value has now been tried in this position, so hand back
Calls
1
Deepest stack
1
Permutations found
0

Complexity

BestO(k!)
AverageO(k!)
WorstO(k!)
Extra spaceO(k)
k! at n=3 predicts 6; this run took 1.

Permutations

Permutations builds every possible ordering of k values by keeping a shared prefix of the values chosen so far. At each call, it tries every value not already in the prefix: it adds that value, recurses to extend the prefix further, and once that recursion has explored everything it can, removes the value again before trying the next one.

When it is the right choice

Generating every permutation is only practical for small k, since there are k! of them — 5! is 120, 10! is over three million. The technique it demonstrates, backtracking, generalises far beyond permutations: constraint satisfaction, the eight queens problem and combinatorial search all follow the same shape of choose, recurse, undo. This page is the first and simplest place to see that shape clearly.

How it works

Worth noticing

Cost

Best
O(k!)
Average
O(k!)
Worst
O(k!)
Extra space
O(k)
Largest input
n = 5

The largest input is a pedagogical ceiling rather than a technical one. This algorithm makes k! calls, and past n = 5 the run stops being something a person can sit and watch — long before it reaches the step limit the tool enforces.

Worth comparing

All recursive algorithms