Power Set Using Bit Manipulation
Pattern: Power set
Loop a mask from 0 to 2^n - 1. For each mask, the subset holds item i exactly when bit i of the mask is 1. Every subset appears once, with no recursion.
The problem
Given an array of different whole numbers, return all its subsets, using the bits of a counter to choose them. For
example, [1, 2, 3] gives [], [1], [2], [1, 2], [3], [1, 3], [2, 3] and [1, 2, 3].
The link above is LeetCode's Subsets, which asks the same question. This guide's function name subsets follows it. The
tests compare after sorting.
Think first
- How many subsets are there, and how many numbers from 0 to
2^n - 1? - How can one number describe which items are in?
- How do you read bit
iof a number?
Hints
Brute force, and why it fails
The recursive take-or-skip method from the Subsets lesson does the same work. Both are O(2ⁿ × n), which is the size of the output.
The key insight
Counting in binary walks through every yes/no pattern of n items in order, so a simple loop replaces the recursion.
Dry run
nums = [1, 2, 3], so masks run from 0 to 7.
The plan
for mask from 0 to 2^n - 1:
subset = [nums[i] for i in 0..n-1 if (mask >> i) & 1]
record subset
Complexity
- Time
O(2ⁿ × n)- Space
O(1)
2ⁿ masks, each read in n steps. Apart from the output, nothing grows.
Edge cases
- One element:
[]and itself. nup to about 20 is practical.- The empty subset is mask 0.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<Integer>> subsets(int[] nums) {
int n = nums.length;
List<List<Integer>> out = new ArrayList<>();
for (int mask = 0; mask < (1 << n); mask++) { // every number from 0 to 2^n - 1 is one subset
List<Integer> subset = new ArrayList<>();
for (int i = 0; i < n; i++) {
if ((mask >> i & 1) == 1) subset.add(nums[i]); // bit i set: nums[i] is in
}
out.add(subset);
}
return out;
}
}C++
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
int n = static_cast<int>(nums.size());
vector<vector<int>> out;
for (int mask = 0; mask < (1 << n); mask++) { // every number from 0 to 2^n - 1 is one subset
vector<int> subset;
for (int i = 0; i < n; i++) {
if (mask >> i & 1) subset.push_back(nums[i]); // bit i set: nums[i] is in
}
out.push_back(subset);
}
return out;
}
};Python
class Solution:
def subsets(self, nums: list[int]) -> list[list[int]]:
n = len(nums)
return [[nums[i] for i in range(n) if mask >> i & 1] # bit i set: nums[i] is in
for mask in range(1 << n)] # every number from 0 to 2^n - 1 is one subsetCommon mistakes
- Looping to
2^ninclusive. - Mixing up which bit stands for which item.
- Using a 32-bit shift for
n ≥ 31.