Lesson 79 of 86AdvancedPro Interactive Lesson

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

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

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.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.