Python BasicsEasy

Generate subsets

Detailed guide and Python implementation for the 'Generate subsets' problem.

Problem Statement

Easy

Write a function generate_subsets(arr) that takes a list of distinct integers and returns all possible subsets (the power set). Return the result as a sorted list of sorted lists. Include the empty subset. Sort each individual subset, then sort the list of subsets by length first, then lexicographically.

Constraints
  • 0 <= len(arr) <= 10
  • All elements in arr are distinct
  • -100 <= arr[i] <= 100

Examples

Example 1
Input
arr = [1, 2, 3]
Output
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
Explanation

An array of 3 elements has 2^3 = 8 subsets, including the empty set and the full set.

Example 2
Input
arr = [1, 2]
Output
[[], [1], [2], [1, 2]]
Explanation

2^2 = 4 subsets.

Example 3
Input
arr = [5]
Output
[[], [5]]
Explanation

2^1 = 2 subsets: the empty set and [5].

Need a Hint?
Consider using Recursion-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.