Skip to content
StackDecode
BacktrackingAnimated

Permutation Generation

Build arrangements by choosing an unused item at each position.

Time

O(n! · n)

Extra space

O(n)

Use it for

All orderings.

How it works

  1. Build the permutation one position at a time.
  2. At each position try every item that has not been used yet.
  3. When all positions are filled, record the permutation.
  4. Backtrack: put the last item back and try the next one. n! results.

Watch it run

Loading animation…