Coding problem · Medium · Backtracking

Subsets

Medium Algorithms & data structures Seen at Meta, Amazon, Bloomberg

Given an array nums of distinct integers, return all possible subsets (the power set), in any order, without duplicates.

Example 1

Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Example 2

Input: nums = [0]
Output: [[],[0]]

Hints

Hint 1

For each element, you either include it or not — 2ⁿ subsets.

Hint 2

Backtrack: choose, recurse, un-choose.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n · 2ⁿ) · Space O(n) recursion (excluding output)

Backtracking: at index i, record the current subset, then for each later element add it, recurse, and remove it. Each of the 2ⁿ subsets is produced once. An iterative alternative: start with [[]] and, for each number, append it to copies of every existing subset.

Reference solution

function subsets(nums) {
  const out = [];
  const cur = [];
  const go = (i) => {
    out.push([...cur]);
    for (let j = i; j < nums.length; j++) {
      cur.push(nums[j]);
      go(j + 1);
      cur.pop();
    }
  };
  go(0);
  return out;
}

Follow-up questions

  • Subsets II: input with duplicates (sort, skip equal siblings).