Subsets solution explained
To generate every subset of a list of distinct numbers, decide for each element whether it is in or out, which gives 2^n subsets. Backtracking builds them by adding one element at a time and recording the partial choice at every step; an iterative loop doubles the list of subsets for each new element; and a bitmask from 0 to 2^n - 1 picks elements by bit. All three take O(n × 2^n) time, which is the size of the output.
By Evin JohnPublished 7 min read
What the problem wants
You are given a list of distinct integers. Return a list of all possible subsets, sometimes called the power set. Each subset is a list of some of the input values; the order of values inside a subset and the order of the subsets do not matter, but no subset may appear twice. The empty subset counts.
| Method | Output order |
|---|---|
| Backtracking with a start index | [], [4], [4, 7], [4, 7, 9], [4, 9], [7], [7, 9], [9] |
| Doubling loop, and also bitmasks | [], [4], [7], [4, 7], [9], [4, 9], [7, 9], [4, 7, 9] |
Both lists hold the same eight subsets. Three elements give 2³ = 8. For an empty input the answer is a list containing one empty subset, not an empty list, which is worth stating before you code.
What it tells the interviewer
Subsets is usually the first backtracking question in a loop, and interviewers use it to see whether you can write the choose, explore, unchoose template cleanly. They also want to hear you reason about output size, because the complexity is set by the 2^n results rather than by clever code. Knowing more than one method, and why bitmasks stop working above about 30 elements in 32-bit arithmetic, separates a memorized answer from an understood one.
Follow-up questions
- The input contains repeated values and the output must not. Sort, then skip a value at the same depth if it equals the previous one. Code below.
- Only subsets of size k. That is combinations; add a size check before recording and stop early when too few elements remain.
- Only subsets whose values add up to a target. Prune branches whose sum already passed the target, if all values are positive.
- Generate them lazily. A generator, or iterating the bitmask, yields one subset at a time without storing all 2^n.
Backtracking with a start index
Picture a tree. The root is the empty choice. From a node, you may add any element that comes after the last one you added. Every node in this tree is a different subset, so you record the current choice the moment you arrive, before going deeper. The start index is what prevents [7, 4] from appearing after [4, 7]: once you are past an element, you never return to it.
def subsets(nums):
result = []
chosen = []
def build(start):
result.append(chosen[:]) # every partial choice is itself a subset
for i in range(start, len(nums)):
chosen.append(nums[i])
build(i + 1)
chosen.pop()
build(0)
return resultAppending chosen[:] rather than chosen is essential. The list chosen is shared and keeps changing, so storing the reference would leave every entry pointing at the same, eventually empty, list.
The doubling loop
Start with a list holding only the empty subset. For each element, take every subset you already have, make a copy with the element added, and append the copies. After the first element you have 2 subsets, after the second 4, and so on. It has no recursion at all, which some interviewers like as a second answer.
def subsets_iterative(nums):
result = [[]]
for x in nums:
result += [s + [x] for s in result] # copy every subset so far, add x
return resultBitmasks in JavaScript
Number the elements 0 to n - 1. Every integer from 0 to 2^n - 1 written in binary is a recipe: bit i set means element i is in. Looping over all those integers lists every subset exactly once.
function subsetsByMask(nums) {
const n = nums.length;
const out = [];
for (let mask = 0; mask < 1 << n; mask++) {
const pick = [];
for (let i = 0; i < n; i++) {
if (mask & (1 << i)) pick.push(nums[i]);
}
out.push(pick);
}
return out;
}JavaScript's bitwise operators work on 32-bit signed integers, so 1 << 31 is already negative. That limit never matters in practice here, because 2^31 subsets would not fit in memory anyway, but saying it shows you know how the operators behave.
When values repeat
With input [6, 2, 6], the plain methods return [6] twice and [2, 6] twice. Sort first so equal values sit together. Then, inside one call, skip a value equal to the one just before it in the loop. Choosing the second 6 at a depth where the first 6 was already tried would only rebuild a subset you have.
def subsets_with_repeats(nums):
nums = sorted(nums)
result, chosen = [], []
def build(start):
result.append(chosen[:])
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue # same value at the same depth would repeat a subset
chosen.append(nums[i])
build(i + 1)
chosen.pop()
build(0)
return resultThe condition is i > start, not i > 0. Using i > 0 would also skip the second 6 when it is taken one level deeper, and [6, 6] would go missing.
Complexity
| Method | Time | Extra space besides the output | Notes |
|---|---|---|---|
| Backtracking | O(n × 2^n) | O(n) recursion and current list | Easy to extend with pruning |
| Doubling loop | O(n × 2^n) | O(1) | No recursion |
| Bitmask | O(n × 2^n) | O(1) | Simple, limited by integer width |
Edge cases
- Empty input: return [[]], one empty subset.
- A single value: [[], [x]].
- Negative values and zero, which change nothing for distinct inputs.
- Repeated values, if the follow-up allows them.
- Large n: the output itself becomes the limit long before the code does.
Common slips
- Storing the shared list instead of a copy.
- Recording only at the leaves of the tree, which drops every subset whose last value is not the final input value.
- Passing i instead of i + 1 to the recursive call, which allows the same element twice.
- Starting the loop at 0 in every call, which produces reordered duplicates.
- Quoting O(2^n) and forgetting the factor of n for copying each subset.
Saying it clearly
Fictional example
- Candidate
- Each element is either in or out, so there are two to the n subsets, and I can't do better than n times two to the n because I have to write them all out.
- Candidate
- I'll backtrack with a start index. Every call records the current choice as a subset, then tries adding each later element, recurses, and removes it.
- Candidate
- The start index stops me from building the same set in a different order. And I record a copy, since the working list keeps changing.
- Interviewer
- What if the input had duplicates?
- Candidate
- I'd sort it and skip a value at the same depth when it matches the previous one in the loop.
Where to go next
Combination Sum keeps the start index but lets a value repeat and adds a target to prune against. Permutations drops the start index and uses a used flag instead, because order now matters. For a different pattern, Last Stone Weight begins the heap problems. You can practice these in JavaScript or Python interview prep too.
Natively as a practice partner
When a backtracking problem refuses to click, Natively can read it from a screenshot and describe the decision tree and the template in its overlay on Mac or Windows. Ask for a hint rather than the full answer if you want to keep the struggle that makes it stick. For spoken mock interviews, the transcript lets you check whether you explained the start index before writing code. More about Natively for coding interviews.
Questions people ask
How many subsets does a list of n elements have?
2^n, because each element is independently in or out. The empty subset and the full list are both included.
What is the time complexity of generating all subsets?
O(n × 2^n). There are 2^n subsets and copying each one into the output takes up to n steps, so no method can do better.
How do you generate subsets without duplicates when values repeat?
Sort the input, then in each recursive call skip a value that equals the previous value in the same loop. That keeps one branch per distinct value at each depth.
Is backtracking or bitmask better for Subsets?
Both are O(n × 2^n). Backtracking is easier to extend with pruning and constraints. Bitmasks are short and iterative but tied to integer width.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
