Subsets
Problem Link
Problem Statement
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution must not contain duplicate subsets. Return the solution in any order.
Examples
Example 1:
Input: nums = [1,2,3]
Output:
[
[],
[1], [2], [3],
[1,2], [1,3], [2,3],
[1,2,3]
]
Example 2:
Input: nums = [0]
Output: [[], [0]]
Constraints
-
1 <= nums.length <= 10 -
-10 <= nums[i] <= 10 -
All elements of
numsare unique
Intuition
Every element has two choices: include it or exclude it.
So for n elements, total subsets = 2ⁿ.
This matches the number of binary numbers from 0 to 2ⁿ - 1.
We can map each bit in a binary number to an element in the array:
- If the
j-thbit ofiis set → includenums[j]in current subset
This technique is called bitmasking.
Approach: Bitmasking
-
For each number
ifrom0to2ⁿ - 1(inclusive), treat it as a bitmask. -
For each bit
jini:- If the bit is set → include
nums[j]in the current subset
- If the bit is set → include
-
Add the generated subset to the result list.
Java Code
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
int n = nums.length;
for (int i = 0; i < (1 << n); i++) {
List<Integer> in = new ArrayList<>();
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) > 0) {
in.add(nums[j]);
}
}
ans.add(in);
}
return ans;
}
}
Time and Space Complexity
| Metric | Value |
|---|---|
| Time Complexity | O(n × 2ⁿ) |
| Space Complexity | O(n × 2ⁿ) |
| Explanation | 2ⁿ subsets, each of size up to n |
Dry Run
Input: nums = [1, 2]
- Total subsets =
2² = 4→i = 0 to 3
-
i = 0 →
00→[] -
i = 1 →
01→[1] -
i = 2 →
10→[2] -
i = 3 →
11→[1, 2]
Output: [[], [1], [2], [1, 2]]
Conclusion
This problem is a classic illustration of using bitmasking to generate all combinations:
-
It avoids recursion and backtracking
-
It's efficient and clean for small inputs (
n <= 10) -
Understanding this lays the groundwork for more complex bitmask-based problems like subsets with conditions, K-subsets, etc.