Subsets

medium

Given an integer array nums of distinct elements, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. You may return the subsets in any order.

Hints

How many subsets does an n-element set have? That number is a strong hint.
Each element is either in or out — that's one bit per element.
Loop every integer from 0 to 2^n - 1 and let its set bits choose the elements.

Common doubts

Each of the n elements is independently in or out — 2 choices each, so 2 x 2 x ... x 2 = 2^n combinations, one per subset.
No. Distinct masks give distinct bit patterns, and the elements are distinct, so every subset is generated exactly once.
By convention bit j (checked with mask & (1 << j)) controls nums[j]. Any fixed assignment works as long as it's consistent.

Interview follow-ups

Then distinct masks can produce equal subsets. Sort the input and skip a value when it repeats and its predecessor wasn't taken, or dedup the results.
Group masks by popcount (number of set bits): all masks with k bits set give the size-k subsets. Iterate popcounts 0..n.

Fun facts

  • This bijection between subsets and n-bit numbers is why a set's power set has size 2^n — the same 2^n that appears everywhere in combinatorics.
  • Iterating a mask's own sub-masks with sub = (sub - 1) & mask is a classic extension used in subset-sum dynamic programming.

Asked at

AmazonGoogleMetaMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: nums = [1, 2, 3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
All 2^3 = 8 subsets, one per 3-bit pattern from 000 to 111. Any order is accepted.
Example 2
Input: nums = [0]
Output: [[],[0]]
The two subsets of a single element: without it and with it.
Constraints

- 1 <= nums.length <= 10 - -10 <= nums[i] <= 10 - All the numbers of nums are unique.

Solve this problem →