Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get an array nums of distinct integers (no value repeats). Return every subset of it. A subset is any selection of the elements: none of them, some of them, or all of them. Order doesn't matter, so [1, 2] and [2, 1] are the same subset and must appear only once. You can return the subsets in any order.
The array has at most 10 numbers, so the answer has at most 2¹⁰ = 1024 subsets. That tiny limit is a signal: the problem expects you to list everything.
Example: nums = [1, 2, 3] → [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]. That's 8 subsets, which is 2³.
Start with brute force
Here the "brute force" is already close to optimal, because the output itself has 2ⁿ subsets. You can't print 2ⁿ things in less than 2ⁿ steps.
One way to list them all is with bitmasks. Count from 0 to 2ⁿ − 1. Each number's binary digits say which elements to include: 101 means "take element 0 and element 2". That works, and it's a nice follow-up answer. But it doesn't teach you the tool you'll need for the rest of this stage. Combination Sum, Permutations and Word Search don't have a neat bitmask shortcut. They all use backtracking, so learn it here, on the simplest problem.
Building the intuition
Think about how you'd list the subsets of [1, 2, 3] by hand without missing any. You'd probably go in an organised way:
- Start with nothing:
[]. - Things starting with 1:
[1], then[1, 2], then[1, 2, 3], then back up and try[1, 3]. - Things starting with 2 (and no 1, you've already done those):
[2],[2, 3]. - Things starting with 3:
[3].
Notice two rules you followed without thinking:
- After you pick a number, you only add numbers to its right. That's what stops you from writing
[2, 1]after[1, 2]. - "Back up" is a real step. After
[1, 2, 3]you removed the 3, then the 2, and tried 3 in the 2's place.
Draw it as a tree. Each node is the list so far. Each edge adds one number to the right of the last one picked:
[]
/ | \
[1] [2] [3]
/ \ |
[1,2] [1,3] [2,3]
|
[1,2,3]Count the nodes: 8. Every node is an answer, not only the leaves. So the code just has to walk this tree and save each node it visits.
Walking the tree means: choose a number (go down an edge), explore everything below it, then un-choose it (come back up) so the path is clean for the next branch. That's backtracking.
The optimal approach
- Keep one shared list
path(the current node) and aresultlist. - Write
backtrack(start):- Append a copy of
pathtoresult. You've arrived at a node, and every node is a subset. - For each
ifromstartton − 1:- Choose: push
nums[i]ontopath. - Explore: call
backtrack(i + 1). - Un-choose: pop
nums[i]offpath.
- Choose: push
- Append a copy of
- Call
backtrack(0)and returnresult.
The subtle detail is the copy. path is one list that keeps changing. If you append path itself, result ends up holding eight references to the same list, which is empty by the end. In Python write path[:], in Java new ArrayList<>(path), in JavaScript [...path]. C++'s push_back(path) already copies.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = []
path = [] # the subset we are building right now
def backtrack(start: int) -> None:
# Every node of the decision tree is a valid subset, so record it on arrival
result.append(path[:]) # copy: path keeps changing after this
for i in range(start, len(nums)):
path.append(nums[i]) # choose
backtrack(i + 1) # explore: only later elements, so no repeats
path.pop() # un-choose
backtrack(0)
return resultclass Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> result;
vector<int> path; // the subset we are building right now
backtrack(nums, 0, path, result);
return result;
}
private:
void backtrack(const vector<int>& nums, int start, vector<int>& path, vector<vector<int>>& result) {
// Every node of the decision tree is a valid subset, so record it on arrival
result.push_back(path); // push_back copies the vector
for (int i = start; i < (int)nums.size(); i++) {
path.push_back(nums[i]); // choose
backtrack(nums, i + 1, path, result); // explore: only later elements, so no repeats
path.pop_back(); // un-choose
}
}
};class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(nums, 0, new ArrayList<>(), result);
return result;
}
private void backtrack(int[] nums, int start, List<Integer> path, List<List<Integer>> result) {
// Every node of the decision tree is a valid subset, so record it on arrival
result.add(new ArrayList<>(path)); // copy: path keeps changing after this
for (int i = start; i < nums.length; i++) {
path.add(nums[i]); // choose
backtrack(nums, i + 1, path, result); // explore: only later elements, so no repeats
path.remove(path.size() - 1); // un-choose (by index, not by value)
}
}
}/**
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function (nums) {
const result = [];
const path = []; // the subset we are building right now
const backtrack = (start) => {
// Every node of the decision tree is a valid subset, so record it on arrival
result.push([...path]); // copy: path keeps changing after this
for (let i = start; i < nums.length; i++) {
path.push(nums[i]); // choose
backtrack(i + 1); // explore: only later elements, so no repeats
path.pop(); // un-choose
}
};
backtrack(0);
return result;
};Dry run
nums = [1, 2, 3]. "Save" means appending a copy of path to result.
| Step | Call | Action | path after | Saved so far |
|---|---|---|---|---|
| 1 | bt(0) | save | [] | [] |
| 2 | bt(0), i = 0 | choose 1 → bt(1), save | [1] | [], [1] |
| 3 | bt(1), i = 1 | choose 2 → bt(2), save | [1, 2] | + [1, 2] |
| 4 | bt(2), i = 2 | choose 3 → bt(3), save; loop is empty | [1, 2, 3] | + [1, 2, 3] |
| 5 | back in bt(2) | un-choose 3, loop ends | [1, 2] | |
| 6 | back in bt(1) | un-choose 2; i = 2: choose 3 → save | [1, 3] | + [1, 3] |
| 7 | back in bt(1) | un-choose 3, loop ends | [1] | |
| 8 | back in bt(0) | un-choose 1; i = 1: choose 2 → save | [2] | + [2] |
| 9 | bt(2) | choose 3 → save | [2, 3] | + [2, 3] |
| 10 | back in bt(0) | un-choose down to []; i = 2: choose 3 → save | [3] | + [3] |
Eight saves, eight subsets, and none repeated.
Complexity
- Time: O(n · 2ⁿ). There are 2ⁿ nodes in the tree, one per subset. At each node we copy
path, which has up tonelements. - Space: O(n) extra, not counting the output. The recursion goes at most
nlevels deep, andpathholds at mostnnumbers. The output itself is O(n · 2ⁿ).
Edge cases and traps
- Appending
pathinstead of a copy. It's the most common bug in every backtracking problem. You get a list of empty lists. - Forgetting the empty subset. It's an answer too. Saving on arrival, before the loop, handles it.
- Looping from 0 instead of
start. You'd build[2, 1]as well as[1, 2], and[1, 1]too. - Recursing with
start + 1instead ofi + 1. After pickingnums[i], the next pick must come afteri, not afterstart. - Java's
path.remove(x). On aList<Integer>,remove(int)removes by index. Always writepath.remove(path.size() - 1).
Say it in the interview
"There are 2ⁿ subsets, so I have to generate all of them, and the goal is to do it without duplicates. I'll backtrack. I keep a current path. Every time I enter the recursion I save a copy, because every node of the decision tree is a subset. Then I try adding each element from a start index onward, recurse with the next index, and pop it off afterwards. Only moving rightward means each set is built in one order only. That's O(n · 2ⁿ) time, which matches the output size, and O(n) extra space for the recursion."
Follow-ups interviewers ask
- "Can you do it without recursion?" Yes, with bitmasks: for every
maskfrom0to2ⁿ − 1, includenums[i]when bitiis set. Or build iteratively: start with[[]], and for each number, add a copy of every existing subset with that number appended. - "What if
numshas duplicates?" (That's LeetCode's Subsets II.) Sort first. Then inside the loop, skipnums[i]wheni > startandnums[i] == nums[i − 1], so a value is only chosen once at each tree level. - "Only subsets of size k?" Same tree, but save only when
len(path) == k, and stop going deeper once you reachk.
Practise the same idea
This is Day 69 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free