Generating Permutations by Backtracking
Choose an unused element for the next position and release that choice when backtracking.
Core Intuition & How It Works
Backtracking generates all n! orderings of n elements by placing each unused element into the next position and restoring state on backtrack. Tracking a used boolean array or swapping in place explores every ordering cleanly.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n × n!) |
| Space Complexity | O(n) recursion + output |
| Topic Chapter | Chapter 14: Backtracking & Computational Complexity |
| Difficulty Level | Advanced |
Key Pattern to Recognize
To handle duplicate elements cleanly, sort first and skip index i if nums[i] === nums[i-1] and !used[i-1].
Common Pitfalls & Edge Cases
Forgetting to unmark used[i] = false after the recursive call returns, which prunes valid branches.
Real-World & Technical Interview Applications
Schedule ordering, anagram generation, small-n Traveling Salesperson search, and constraint puzzles.