Skip to problem
←

Subsets II

Medium 0 attempts

Return every distinct subset of nums, including the empty subset [].

Each input position can be selected at most once. Repeated values may appear together when the input contains enough copies, but two choices producing the same values form only one distinct subset. Element order does not distinguish subsets.

For [2,2], return [[],[2],[2,2]]: include [2] once, and do not discard the valid two-copy subset.

Subsets and the elements within each subset may be returned in any order.

Function contract

Implement subsetsWithDup(nums).

Output: Return each distinct subset exactly once, including []. Each value can appear no more often than it occurs in nums. Ordering of subsets and elements within a subset is ignored.

Example 1

Input
nums = [1,2,2]
Output
[[],[1],[1,2],[1,2,2],[2],[2,2]]

Example 2

Input
nums = [0]
Output
[[],[0]]
Constraints
  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10

Sort the array first so duplicates are adjacent. During backtracking, skip an element if it's the same as the previous one at the same recursion depth — this prevents duplicate subsets from being generated.

javascript
function subsetsWithDup(nums) {
  nums.sort((a, b) => a - b);
  const result = [];

  function backtrack(start, current) {
    result.push([...current]);
    for (let i = start; i < nums.length; i++) {
      if (i > start && nums[i] === nums[i - 1]) continue;
      current.push(nums[i]);
      backtrack(i + 1, current);
      current.pop();
    }
  }

  backtrack(0, []);
  return result;
}

Time: O(n * 2^n) — up to 2^n subsets, each copied in O(n). Auxiliary space: O(n) for the recursion stack and current subset (plus sorting workspace).

Output space: O(n × 2^n) in the worst case when all values are distinct.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript