Back to Practice Dashboard
Python BasicsEasy

Generate subsets

Learn how to solve the 'Generate subsets' problem. This detailed resource details brute force and optimized approaches.

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?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

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

Open in Editor