Given an integer array nums of unique elements, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Note: The power set of a set is the set of all its subsets, including the empty set and the set itself.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
💡 Note: All possible combinations of including/excluding each element. Empty set and full set are both included.
Example 2 — Two Elements
$ Input: nums = [0]
Output: [[],[0]]
💡 Note: With one element, we have 2¹ = 2 subsets: empty set and the single element.
Example 3 — Larger Array
$ Input: nums = [1,2]
Output: [[],[1],[2],[1,2]]
💡 Note: With two elements, we have 2² = 4 subsets representing all include/exclude combinations.

Constraints

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

Visualization

Tap to expand
Subsets - Power Set Generation INPUT Integer Array (nums) 1 idx 0 2 idx 1 3 idx 2 n = 3 elements All unique values Power Set Size 2^n = 2^3 = 8 subsets nums = [1, 2, 3] ALGORITHM STEPS 1 Start Empty Begin with result = [[]] 2 Iterate Elements For each num in nums 3 Extend Subsets Add num to each existing 4 Merge Results Append new subsets Building Process Start: [[]] +1: [[], [1]] +2: [[], [1], [2], [1,2]] +3: [[], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]] FINAL RESULT All 8 Subsets (Power Set) [] [1] [2] [1,2] [3] [1,3] [2,3] [1,2,3] OK - Complete! 8 subsets generated Output: [[], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]] Time: O(n * 2^n) | Space: O(n * 2^n) Key Insight: Iterative approach: For each element, create new subsets by adding it to all existing subsets. Each element has two choices: include or exclude. This gives us 2^n total subsets. Alternative: Use backtracking or bit manipulation (each number 0 to 2^n-1 represents a subset). TutorialsPoint - Subsets | Optimal Iterative Solution
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
508.9K Views
High Frequency
~15 min Avg. Time
15.4K 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