InterviewPrepKit

Home / Coding / Backtracking

Subsets

medium Original β†—
Solving tips
  • This is the canonical independent-binary-choice-per-element problem: each of the n elements is either in or out, giving exactly 2^n subsets.
  • In the backtracking version record path[:] at EVERY node (not just leaves), since subsets have all sizes, and recurse from i+1 to avoid duplicates.
  • Know all three interchangeable tools: include/exclude recursion, iterative doubling (extend every existing subset with the new element), and bitmask enumeration over 0..2^n-1.
  • All are O(n * 2^n) time; append snapshots (path[:]), never the live path reference.

Problem

Given an array nums of distinct integers, return all possible subsets β€” the power set. This includes the empty subset and the full array itself.

The result must not contain duplicate subsets, and you may return the subsets and the elements within each subset in any order.

For an input of size n, there are exactly 2^n subsets (each element is independently either in or out).

Examples

  • Input: nums = [1, 2, 3] β†’ Output: [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]] All 2^3 = 8 subsets, from empty to the full set.
  • Input: nums = [0] β†’ Output: [[], [0]] A single element gives just the empty set and itself.
  • Input: nums = [9, 8] β†’ Output: [[], [9], [8], [9,8]] All 4 subsets of a two-element array.

Constraints

  • 1 <= nums.length <= 10.
  • -10 <= nums[i] <= 10.
  • All integers in nums are distinct.

With n <= 10, the power set has at most 2^10 = 1024 subsets β€” the output size is inherently exponential.

Think about it first

Hint 1 Every element faces a binary decision independent of the others: include it or skip it. How many total combinations of such yes/no choices are there?
Hint 2 Walk the elements left to right, carrying a partial subset. At each element, branch: recurse with it added, then recurse without it. When you run out of elements, record the current partial subset.
Hint 3 An alternative to the include/exclude branching: start with `[[]]` and, for each new element, append it to copies of every subset built so far. Or, since there are exactly `2^n` subsets, map each integer from `0` to `2^n - 1` to a subset via its set bits.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.