InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Backtracking

Subsets

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug