Generate All Possible Subsets (Power Set)

Given an integer array nums containing unique elements, your task is to return all possible subsets of the array, also known as the power set.

A subset is any combination of elements from the original array, including the empty set and the array itself. The order of subsets in the result doesn't matter, but each subset should appear exactly once.

Example: For array [1,2,3], the power set contains 8 subsets: [], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]

๐Ÿ’ก Fun fact: An array of n elements always has exactly 2n subsets!

Input & Output

example_1.py โ€” Basic Case
$ Input: [1,2,3]
โ€บ Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
๐Ÿ’ก Note: For 3 elements, we get 2ยณ = 8 subsets. Each element can either be included or excluded from each subset.
example_2.py โ€” Single Element
$ Input: [0]
โ€บ Output: [[],[0]]
๐Ÿ’ก Note: With one element, we have 2ยน = 2 subsets: the empty set and the set containing the single element.
example_3.py โ€” Empty Array Edge Case
$ Input: []
โ€บ Output: [[]]
๐Ÿ’ก Note: An empty array has only one subset: the empty set itself. This follows 2โฐ = 1.

Constraints

  • 1 โ‰ค nums.length โ‰ค 10
  • -10 โ‰ค nums[i] โ‰ค 10
  • All the numbers of nums are unique

Visualization

Tap to expand
Power Set Generation for [1,2,3]Bit Representation000 โ†’ []001 โ†’ [1]010 โ†’ [2]011 โ†’ [1,2]100 โ†’ [3]101 โ†’ [1,3]110 โ†’ [2,3]111 โ†’ [1,2,3]Decision Tree (Backtracking)[][1][]+1-1๐Ÿ• Pizza AnalogyToppings: [Pepperoni, Cheese, Mushroom]Each topping: Include or SkipResult: All possible pizzasFrom plain (no toppings) tofully loaded (all toppings)Total Subsets: 2^n where n = array length
Understanding the Visualization
1
Binary Choice
Each element has 2 options: include or exclude
2
Systematic Generation
Use either backtracking or bit manipulation to explore all 2^n possibilities
3
Complete Power Set
Collect all generated subsets from empty set to full set
Key Takeaway
๐ŸŽฏ Key Insight: Every element has exactly 2 choices (include/exclude), giving us 2^n total combinations. Both bit manipulation and backtracking systematically explore all possibilities.
Asked in
Meta 42 Amazon 38 Google 35 Microsoft 28 Apple 22
89.3K Views
Very High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen