Python 0078.py
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = [[]]
for i in nums:
next = []
for j in result:
next.append(j + [i])
result += next
return result
Difficulty
and has an acceptance rate of about 83% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
- Bit Manipulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation generates all possible subsets (the power set) of a list of integers. It follows an iterative construction where the current collection of subsets is expanded step-by-step as each element of the input list is processed. The algorithm starts with the empty subset and, for every new number, creates new subsets by appending that number to each existing subset. The final collection contains every combination, including the empty set and the full set.
Key Steps
Initialization of the result container
The algorithm begins by creating a list that holds a single element: the empty subset. This serves as the base case for the iterative expansion.
result = [[]]
Iteration over the input numbers
A for loop walks through each integer in the input list nums. The loop variable i represents the current element that will be added to existing subsets.
for i in nums:
Construction of new subsets for the current element
Inside the outer loop, a temporary list next is created to store the subsets that include the current element i. Another for loop iterates over the subsets already present in result. For each existing subset j, a new subset is formed by concatenating j with a list containing i. The new subset is appended to next.
next = []
for j in result:
next.append(j + [i])
Merging the newly created subsets
After all new subsets for the current element have been generated, they are merged back into result using the += operator. This operation extends result in place, avoiding the creation of an additional intermediate list.
result += next
Returning the complete collection
When the outer loop has processed every element of nums, result holds the full power set, which is then returned.
return result
Edge Cases Handled
When the input list nums is empty, the outer loop does not execute. The initial result containing only the empty subset remains unchanged, and the function correctly returns [[]], representing the power set of an empty set.
If nums contains duplicate values, the algorithm treats each occurrence as a distinct element because it processes the list positionally. Consequently, subsets that differ only by the position of identical values are generated separately, preserving the combinatorial definition of subsets for a multiset.
For very large input lists, the algorithm still produces the correct result because it does not rely on recursion or external data structures that could overflow the call stack. The iterative approach ensures that memory allocation follows the natural growth of the power set.
Performance Optimizations Observed
The implementation avoids recursive calls, which eliminates the overhead associated with function call stacks and reduces the risk of hitting recursion limits for deep inputs.
By constructing the new subsets in a temporary list next and then extending result with +=, the code performs a single list concatenation per input element. This in-place extension minimizes the number of intermediate list objects created during the process.
The use of list concatenation j + [i] creates a new list for each new subset, but it does so only once per subset. There is no repeated copying of the entire result list; instead, each existing subset is copied only when it is extended with the current element.
Overall, the algorithm leverages Pythonβs built-in list operations, which are implemented in C and provide efficient memory handling for the frequent append and extend actions required to build the power set.
ELI5 - Simplified Explanation
Imagine you have a big box of colorful building blocks and you want to see all the different ways you can pick them. First, you keep an empty space set aside just in case you want to pick nothing at all. Every time you pick up a new block from your pile, you look at all the groups you have already made and add this new block to each one of them. By doing this, you create even more groups. You keep doing this for every single block in your pile until you have explored every possible way to combine them. This process creates a big list that shows every possible group of blocks you could have chosen.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||||
| WalkCCC | C++ | Python | Java | ||||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | |||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | aylei | Rust | |||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| bujosa | Python | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| Dijkstra-Edu | Java | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C++ | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| MacJim | C++ | ||||||||||||
| martianoff | Scala | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| bujosa | Python | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| Dijkstra-Edu | Java | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C++ | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| MacJim | C++ | ||||||||||||
| martianoff | Scala | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 90: Subsets II
- problem 320: Generalized Abbreviation
- problem 784: Letter Case Permutation
- problem 2044: Count Number of Maximum Bitwise-OR Subsets
Solved On The Same Day
- problem 195: Tenth Line
- problem 53: Maximum Subarray
- problem 56: Merge Intervals
- problem 86: Partition List
- problem 89: Gray Code
- problem 90: Subsets II
- problem 98: Validate Binary Search Tree
- problem 179: Largest Number
- problem 456: 132 Pattern
- problem 473: Matchsticks to Square
- problem 542: 01 Matrix
- problem 916: Word Subsets
- problem 1930: Unique Length-3 Palindromic Subsequences
- problem 233: Number of Digit One
- problem 295: Find Median from Data Stream
- problem 315: Count of Smaller Numbers After Self
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality