Skip to main content

Subsets II

Given an integer array that may contain duplicates Return all possible unique subsets (the power set) Example: nums = [1,2,2] => [[],[1],[1,2],[1,2,2],[2],[2,2]]

Sorting first is what makes duplicates visible. I skip a repeated value at the same depth, so no subset shows up twice.

Examples

You write

subsets_with_dup(nums: List[int])

  1. Example 1

    Input
    nums = [1,2,2]
    returns
    [[],[1],[1,2],[1,2,2],[2],[2,2]]
  2. Example 2

    Input
    nums = [0]
    returns
    [[],[0]]

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Backtracking

I reach for it when

  • The question asks for all combinations, permutations or placements.
  • You make a choice, explore it, and may need to take it back.

Say this before you type. Say the choice, the stopping rule, and the earliest moment you can prune.

All 15 Backtracking problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Generate All Unique Subsets (With Duplicates)medium