Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Compute factorial recursivelyE02. Generate first N Fibonacci numbers recursivelyE03. Find all subsets of a setE

Problem No 3

Find all subsets of a set

Easy

10 minute session

Summary

Generate all subsets (the power set) of a list of unique elements using recursion/backtracking.

Problem statement

Given a list of unique elements nums, return a list containing all possible subsets. Each subset should preserve the element order as in the input. To make outputs deterministic, return the list of subsets sorted by increasing subset length and then lexicographically by the subset elements (i.e., key = (len(subset), tuple(subset))). For example, for [1,2] the result should be [[], [1], [2], [1, 2]]. Use a recursive/backtracking approach.

Task

Implement subsets(nums) that returns all subsets (as lists) sorted first by length then lexicographically to ensure deterministic order.

Examples

Example 1

Input

subsets([1, 2])

Output

[[], [1], [2], [1, 2]]

Explanation

All subsets are: empty, singletons, and the full set. Sorted by length then lexicographically.

Input format

A single list of unique elements, e.g., [1, 2, 3].

Output format

A list of lists representing all subsets, sorted by (length, lexicographic).

Constraints

0 ≤ len(nums) ≤ 10 in tests. Use recursion/backtracking; the number of subsets is 2^n.

Samples

Sample input 0

subsets([1, 2, 3])

Sample output 0

[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]

Explanation 0

All 8 subsets of [1,2,3] sorted as required.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:48 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.