Generating Subsets by Backtracking
At each position, branch between including the current element and leaving it out.
Core Intuition & How It Works
Backtracking generates all 2ⁿ subsets (the power set) of a collection by deciding at each element to include it or skip it, undoing each choice upon returning from recursion.
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 × 2ⁿ) |
| Space Complexity | O(n) recursion + output |
| Topic Chapter | Chapter 14: Backtracking & Computational Complexity |
| Difficulty Level | Advanced |
Key Pattern to Recognize
Copy the current path when recording a subset, and sort + skip adjacent duplicates at the same depth when input has repeated values.
Common Pitfalls & Edge Cases
Pushing a mutable reference to the working array into results without cloning it, causing every saved subset to end up empty.
Real-World & Technical Interview Applications
Feature subset selection, combinatorial search, and bitmask enumeration foundations.