Subsets

Medium

Extra practice. This problem has no walkthrough slides. Try solving it with the pattern template on your own, and lean on the hints if you get stuck.

Question

Given a list of distinct integers, build every grouping you can make by picking any number of values from the list. This includes a grouping with nothing in it and a grouping with every value in it.

Return all of these groupings together as a single list. The order of the groupings in your answer does not matter, and neither does the order of the values inside each grouping.

Input: nums = [1, 2]

Output: [[], [1], [2], [1, 2]]

There are 4 groupings: the empty grouping, each single value on its own, and both values together.

Input: nums = [4, 9, 5]

Output: [[], [4], [9], [5], [4, 9], [4, 5], [9, 5], [4, 9, 5]]

With 3 distinct values, there are 8 groupings in total: one for each way you can either include or skip a value.

Input: nums = []

Output: [[]]

An empty list still has one grouping: the empty grouping itself.

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

How many groupings should be returned for nums = [7, 8, 9]?
6
7
8
9

Take a moment to understand the problem and think of your approach before you start coding.