Skip to content

Algorithms

Backtracking (Permutations)

O(n!) time to generate all permutations of n items — there really are that many orderings · O(n) space for the recursion depth, not counting the output itself.

The idea, in plain English

Backtracking is like trying on outfits. Put on one item, then see if you can finish the rest of the outfit. If you hit a dead end, take that item off — this step is the 'backtrack' — and try something else. Generating every permutation, every possible ordering of a list, works the same way. Place one item in the next open slot, try to fill the rest, then undo it and try the next item instead.

How it works

  1. 1Keep a 'path', the ordering built so far, and a list of 'remaining' items not yet placed.
  2. 2For each remaining item, place it in the path. Then try to fill the rest of the path with what is left, using the same steps again.
  3. 3When no items remain, the path is one full permutation. Record it, undo the last placement — the 'backtrack' step — and try the next remaining item instead.

When you'd use it

Use it to generate every possible arrangement or combination — permutations, subsets, or puzzle solutions like Sudoku or N-Queens. Use it anywhere you need to explore every branch of choices and drop the ones that do not work out.

Common beginner mistakes

  • Forgetting to undo the choice after exploring further — the actual backtrack step. Without it, leftover state leaks into the next branch.
  • Not realizing that n! grows explosively. Permutations of just 10 items already total 3.6 million orderings.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Permutations: 123 132 213 231 312 321

See it in motion

Watch it exploreBacktracking{2, 3, 1}O(n!) time to generate all permutations of n items — there really are that many orderings · O(n) space for the recursion depth, not counting the output itself.
·231133211212332
Path (chosen)
empty
Remaining
231

Start with an empty path; every element is still available.

Permutations found
—
0/6
Found
0
Depth
1/38
Step
0.0s
Time
On the current pathCompleted permutationExplored & undoneNot yet tried

Not sure this is the right topic? See the learning paths → or where this leads →