AlgoInsight

DSA problem

Subsets II

MediumBacktrackingPattern: Backtrackingtop600AmazonMicrosoftGoogleAdobeBloomberg

Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets, and the answer may be returned in any order. For example, with nums = [1,2,2], the subset [1,2] should appear only once even though there are two 2s in the input.

This is the duplicates-allowed variant of the standard subsets problem. A brute-force fix would enumerate every subset, push them into a set keyed by their sorted tuple, and return the deduplicated list. But that wastes time and memory generating subsets we are going to throw away — and it is also a leaky API, because the work scales with 2^n even when the unique answer is much smaller.

The clean fix is the standard "sort, then skip duplicates at the same recursion level" pattern. After sorting, any equal-value run sits in a contiguous block of indices. When the recursive loop picks an index, the first equal-value index in that block starts a fresh branch; every other index in the block (at the same depth) would generate an identical subtree, so we skip it with the rule if i > start && nums[i] == nums[i - 1] continue.

Everything else follows the regular subsets template: at every node snapshot path into the results, then iterate i from start to n - 1, push nums[i], recurse on i + 1, and pop. The dedupe rule fires O(n) times per level so total time stays at O(n * 2^n) worst case and space is O(n) for recursion and working buffer.

Examples

Example 1
Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
Explanation: Six unique subsets. The subset [1,2] appears once even though either 2 in the input could fill that role.
Example 2
Input: nums = [0]
Output: [[],[0]]
Explanation: A single element gives two subsets: empty and singleton.
Example 3
Input: nums = [4,4,4,1,4]
Output: [[],[1],[1,4],[1,4,4],[1,4,4,4],[1,4,4,4,4],[4],[4,4],[4,4,4],[4,4,4,4]]
Explanation: After sorting to [1,4,4,4,4], the unique subsets are determined by how many 4s we pick (0–4) optionally combined with the single 1.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

backtrackingarraysortingrecursion

Browse all DSA problems