Problem 78

Abstract / Summary

Given a set of numbers generate all possible groups including the empty group and the group itself

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
9 lines | 266 bytes | submitted August 17, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 83% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Bit Manipulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.44 | σ = 0.83

Complexity Analysis

Time: exponential
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
62 links | 47 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Subsets (LeetCode 78) | Full solution with backtracking examples | Interview | Study Algorithms'
Nikhil Lohia 16 mins
Subsets (LeetCode 78) | Full solution with backtracking examples | Interview | Study Algorithms
YouTube video 'Subsets | Simple Story To Code | Leetcode 78 | Recursion Concepts And Questions | Video 17'
codestorywithMIK 23 mins
Subsets | Simple Story To Code | Leetcode 78 | Recursion Concepts And Questions | Video 17
YouTube video 'LeetCode Tutorial 78. Subsets'
GoodTecher 16 mins
LeetCode Tutorial 78. Subsets
YouTube video 'Print all subsets of array πŸ”₯ | Leetcode 78 |  Recursion | Medium'
Ayushi Sharma 13 mins
Print all subsets of array πŸ”₯ | Leetcode 78 | Recursion | Medium
YouTube video 'Subsets - LeetCode 78 - Python'
Deepti Talesra 7 mins
Subsets - LeetCode 78 - Python
YouTube video 'Subsets | Leet code 78 | Theory explained + Python code | July Leet code day 11'
Sai Anish Malla 8 mins
Subsets | Leet code 78 | Theory explained + Python code | July Leet code day 11
YouTube video 'LEETCODE 78 (JAVASCRIPT) | SUBSETS I'
Andy Gala 14 mins
LEETCODE 78 (JAVASCRIPT) | SUBSETS I
YouTube video '78. Subsets | Backtracking Series | INTRODUCTION | LEETCODE'
code Explainer 14 mins
78. Subsets | Backtracking Series | INTRODUCTION | LEETCODE
YouTube video 'Leetcode 78 - Subsets (JAVA Solution Explained!)'
LC Bear 9 mins
Leetcode 78 - Subsets (JAVA Solution Explained!)
YouTube video 'Subsets - LeetCode 78 - JavaScript'
AlgoJS 6 mins
Subsets - LeetCode 78 - JavaScript
YouTube video 'subsets | subsets leetcode | leetcode 78'
Naresh Gupta 9 mins
subsets | subsets leetcode | leetcode 78
YouTube video 'Subsets in Telugu | Leetcode 78 | Iterative, Backtracking Approaches | Power Set DSA | srkcodes'
Srk Codes 13 mins
Subsets in Telugu | Leetcode 78 | Iterative, Backtracking Approaches | Power Set DSA | srkcodes
YouTube video 'Subsets | Day 11 Cascading Backtracking Lexicographic | [ July LeetCoding Challenge] [ Leetcode #78]'
Algorithms Made Easy 6 mins
Subsets | Day 11 Cascading Backtracking Lexicographic | [ July LeetCoding Challenge] [ Leetcode #78]
YouTube video 'Subsets - Leetcode 78 - Java'
Code With K5KC 7 mins
Subsets - Leetcode 78 - Java
YouTube video 'Subsets | Leetcode 78 | Live coding session πŸ”₯πŸ”₯πŸ”₯ | Live coding session πŸ’―πŸ’―'
Coding Decoded 9 mins
Subsets | Leetcode 78 | Live coding session πŸ”₯πŸ”₯πŸ”₯ | Live coding session πŸ’―πŸ’―
YouTube video 'Subsets  (LeetCode  78) (Recursion + Backtracking, Bit Manipulation)'
CodeWithARB 41 mins
Subsets (LeetCode 78) (Recursion + Backtracking, Bit Manipulation)
YouTube video 'LeetCode 78 πŸ”₯ Subsets | Backtracking Approach | Java Solution + Dry Run | SDE Interview Sheet'
Study Placement 18 mins
LeetCode 78 πŸ”₯ Subsets | Backtracking Approach | Java Solution + Dry Run | SDE Interview Sheet
YouTube video 'Daily Leetcode #1512: May 21, 2024 - 78. Subsets'
Programming Live with Larry 5 mins
Daily Leetcode #1512: May 21, 2024 - 78. Subsets
YouTube video '78. Subsets | May | Java | C++'
Mayur Programming Club 19 mins
78. Subsets | May | Java | C++
YouTube video 'Subsets - Backtracking - Leetcode 78'
Web Coder Abhishek 6 mins
Subsets - Backtracking - Leetcode 78
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

1 easy 12 medium 3 hard
17 solutions   August 17, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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