Lesson 80 of 86AdvancedPro Interactive Lesson

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

MetricComplexity
Time ComplexityO(n × n!)
Space ComplexityO(n) recursion + output
Topic ChapterChapter 14: Backtracking & Computational Complexity
Difficulty LevelAdvanced

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.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.