CodeSpeek

Subsets

Medium · Backtracking

Given an array of distinct integers, return every possible subset of the array, including the empty subset and the array itself. Each subset should be listed exactly once, and the order of subsets or of elements within them does not matter. Only the collection of distinct subsets counts toward correctness.

Examples

Input:  nums = [1,2,3]
Output: [[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
Why:    Every combination of the three elements, from choosing none to choosing all, forms a distinct subset.
Input:  nums = [0]
Output: [[],[0]]
Why:    A single-element array has exactly two subsets: empty and the whole array.
Input:  nums = [5,-3]
Output: [[],[5],[-3],[5,-3]]
Why:    With two elements there are four subsets covering every choice of including or excluding each element.

Constraints

1 <= nums.length <= 10, -10 <= nums[i] <= 10, all elements are distinct

Practise it by voice

Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.

Practise Subsets

This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Subsets. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.