Generate subsets
Detailed guide and Python implementation for the 'Generate subsets' problem.
Problem Statement
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.
- •0 <= len(arr) <= 10
- •All elements in arr are distinct
- •-100 <= arr[i] <= 100
Examples
arr = [1, 2, 3]
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
An array of 3 elements has 2^3 = 8 subsets, including the empty set and the full set.
arr = [1, 2]
[[], [1], [2], [1, 2]]
2^2 = 4 subsets.
arr = [5]
[[], [5]]
2^1 = 2 subsets: the empty set and [5].
Need a Hint?
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.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Generate Random Numbers in Python
Learn how to generate random numbers in Python. Compare randrange, randint, and uniform float generation with seeding control.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.