CodeArchon

mediumBacktrackingFacebookAmazon

Duplicate-Aware Powerset

A merchandise bundler generates every distinct bundle of items from a stock list that may contain duplicates.

Given an integer array nums that may contain duplicates, return all possible subsets (powerset) without duplicates.

Choose approach

1
0
j
2
1
2
2
SetUnique Subsets (1)
[]
1/6
Narrationstep 1 of 6

Emit []

1def subsetsWithDup(nums):
2 nums.sort(); out, cur = [], []
3 def dfs(i):
4 out.append(cur[:])
5 for j in range(i, len(nums)):
6 if j > i and nums[j] == nums[j-1]: continue
7 cur.append(nums[j]); dfs(j+1); cur.pop()
8 dfs(0); return out
Variables
cur=[]
out=1

How to think about it

  1. Sorted order groups duplicates.
  2. Within a single call, pick a duplicate value only once.
  3. Every node in the recursion tree emits a subset.

Edge cases to catch in interview

  • All duplicates -> n+1 subsets.
  • Empty input -> single empty subset.

Examples

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

Try your own input

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