High interview relevanceRoadmap: Advanced
TimeO(2ⁿ) subsets; O(n · 2ⁿ) including copying each one
SpaceO(n) recursion, plus stored output

Why it costs this much

Each item is either included or excluded, so there are 2ⁿ leaves in the recursion tree.

Code

def subsets(nums):
    res, cur = [], []
    def go(i):
        if i == len(nums):
            res.append(cur[:])        # 2^n leaves; each copy costs O(n)
            return
        go(i + 1)                     # exclude nums[i]
        cur.append(nums[i])
        go(i + 1)                     # include nums[i]
        cur.pop()
    go(0)
    return res

Common pitfalls

Copying each result adds a factor of n to the time. Pruning helps in practice but often does not change the worst-case bound.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list