CodeArchon

mediumBacktrackingFacebookAmazonBloomberg

Powerset Expander

A feature-flag planner enumerates every possible on/off combination of distinct toggles.

Given an array of distinct integers, return all possible subsets. The solution set must not contain duplicate subsets.

Choose approach

1
0
i
2
1
3
2
SetSubsets so far (0)
empty
1/24
Narrationstep 1 of 24

Start DFS at index 0.

1def subsets(nums):
2 out, cur = [], []
3 def dfs(i):
4 if i == len(nums):
5 out.append(cur[:]); return
6 cur.append(nums[i]); dfs(i+1); cur.pop()
7 dfs(i+1)
8 dfs(0); return out
Variables
depth=0
cur=[]
outCount=0

How to think about it

  1. Each element contributes an independent binary choice.
  2. Backtrack by popping after the include branch returns.
  3. Depth = n -> leaf emits one subset.

Edge cases to catch in interview

  • Empty input -> single empty subset.
  • Duplicates are forbidden by the problem.

Examples

Example 1[[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]
{"values":[1,2,3]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed