Algorithms · Visualized
Permutations
Backtracking
Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.
Generates every possible ordering of a set of elements. Time: O(n × n!) average, O(n × n!) — n! permutations, each taking O(n) to build worst; space: O(n) for recursion depth, plus O(n × n!) to store all results.
Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.
Permutations
BacktrackingGenerates every possible ordering of a set of elements. Backtracking builds a permutation one element at a time, and whenever it finishes a complete arrangement (or hits a dead end), it 'backtracks' — undoes the last choice — and tries a different option.
How Permutations Works
- Keep a 'current path' list to build a permutation, and a way to track which elements are already used.
- At each step, try every unused element as the next item in the current path.
- Mark that element as used, add it to the path, and recurse to fill the next position.
- If the path length equals the input length, record it as a complete permutation.
- After exploring that choice fully, undo it (remove from path, mark unused again) — this is the 'backtrack' step — and try the next option.
Permutations Worked Example
Input: [1, 2, 3]
Start path=[]. Try 1 → path=[1]. Try 2 → path=[1,2]. Try 3 → path=[1,2,3], complete, record. Backtrack to [1,2], no more options, backtrack to [1]. Try 3 → path=[1,3]. Try 2 → path=[1,3,2], record. Continue this branching for starting with 2 and 3. Final result: all 6 permutations of [1,2,3].
def permutations(a):
out = []
def build(i):
if i == len(a):
out.append(a[:])
return
for j in range(i, len(a)):
a[i], a[j] = a[j], a[i]
build(i + 1)
a[i], a[j] = a[j], a[i]
build(0)
return outBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Permutations Time & Space Complexity
When to Use Permutations
- Generating all possible arrangements for scheduling, password combinations, or puzzle solving.
- Foundation pattern for many other backtracking problems (N-Queens, word search, etc.).
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.