Subsets II
LeetCode 90 · Medium · solution, intuition & step-by-step walkthrough
Sort; skip nums[i] == nums[i−1] when i > index.
This is how I solved Subsets II (LeetCode 90), a medium problem from the Subsets pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Same as Subsets, but sort first so duplicates sit together. At each level, skip a value equal to the previous one at the same level — choosing it would recreate a subset you already built.
Approach
- 1
Sort.
- 2
Record the current subset.
- 3
Loop i from index; skip duplicates at the same level.
- 4
Append, recurse with i+1, pop.
How I solved it
Backtracking with duplicate skipPythonO(n·2ⁿ) time
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res=[]
def dfs(index,ds):
res.append(ds[:])
for i in range(index,len(nums)):
if i!=index and nums[i]==nums[i-1]:
continue
ds.append(nums[i])
dfs(i+1,ds)
ds.pop()
dfs(0,[])
return res
Subsets II — FAQ
What is the intuition behind Subsets II?
Same as Subsets, but sort first so duplicates sit together. At each level, skip a value equal to the previous one at the same level — choosing it would recreate a subset you already built.
How do you solve Subsets II (LeetCode 90)?
1. Sort. 2. Record the current subset. 3. Loop i from index; skip duplicates at the same level. 4. Append, recurse with i+1, pop.
What is the time and space complexity of Subsets II?
Time: O(n · 2ⁿ). Space: O(n). (Accepted approach: Backtracking with duplicate skip.)
What are common mistakes in Subsets II?
The condition is i != index (same level), not i > 0.