Subsets

35 min · subsets()

Picking toppings for a pizza creates more possibilities than it first appears: every topping can be included or left out. An array gives you the same branching choice.

nums holds distinct integers. Build its power set — the collection of every possible subset, where a subset selects zero or more input values.

A few ground rules:

  • Write every subset in ascending numeric order.
  • Include the empty subset [] and the subset containing every value.
  • Return each subset exactly once. The outer list may be in any order.
  • Treat values as choices, not positions; every input value is distinct.

Constraints

  • 1 <= nums.length <= 12
  • -100 <= nums[i] <= 100
  • All values in nums are distinct.

Hints

Count the decisions

Each value has two futures: take it or leave it. With n values, how many complete chains of those decisions exist?

Keep one partial subset

Sort a copy of nums, then carry one growing list through the recursion. At each index, explore the branch that includes the value and the branch that skips it.

Undo before the other branch

After exploring the include branch, remove its last value before you explore the skip branch. That one undo keeps the two branches independent.

Follow-up

Could you produce the subsets one at a time, without keeping the full power set in memory, while preserving ascending order inside each subset?

Visible cases

Examples

Example 1

ready
Input
nums = [
  1,
  2,
  3
]
Expected
[
  [],
  [
    1
  ],
  [
    2
  ],
  [
    3
  ],
  [
    1,
    2
  ],
  [
    1,
    3
  ],
  [
    2,
    3
  ],
  [
    1,
    2,
    3
  ]
]
Why
three independent include-or-skip choices create 2³ = 8 subsets

Example 2

ready
Input
nums = [
  4
]
Expected
[
  [],
  [
    4
  ]
]
Why
one value produces the empty subset and the one-value subset

Example 3

ready
Input
nums = [
  3,
  -1
]
Expected
[
  [],
  [
    -1
  ],
  [
    3
  ],
  [
    -1,
    3
  ]
]
Why
each subset is ascending even when the input isn't

Interview signal

Asked at

AmazonMetaGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite