Python 0416.py
class Solution:
def canPartition(self, nums: List[int]) -> bool:
total = sum(nums)
todo = set([ 0 ])
for n in nums:
next = set()
for t in todo:
next.add(t)
if 2 * (n + t) == total:
return True
if 2 * (n + t) < total:
next.add(n + t)
todo = next
return False
Difficulty
and has an acceptance rate of about 50% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
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 determines whether a list of integers can be split into two subsets whose sums are equal. It first computes the total sum of the input array and then incrementally builds a set of reachable partial sums while scanning the numbers. If at any point a partial sum can be paired with the remaining elements to achieve exactly half of the total, the function returns True. If the scan finishes without finding such a condition, it returns False.
Key Steps
Compute the total sum
total = sum(nums)
The total sum is required to know the target value for each subset, which is half of total. The algorithm does not explicitly compute the half; instead it uses a relational check that avoids floating-point division.
Initialise the reachable-sum set
todo = set([0])
The set todo holds all subset sums that can be formed from the numbers processed so far. Starting with {0} represents the empty subset.
Iterate over each number
for n in nums:
next = set()
for t in todo:
next.add(t)
if 2 * (n + t) == total:
return True
if 2 * (n + t) < total:
next.add(n + t)
todo = next
For each element n, a new set next is prepared. The inner loop examines every previously reachable sum t.
-
The statement
next.add(t)carries forward the existing sum unchanged, representing the choice of not includingn. -
The condition
2 * (n + t) == totalchecks whether addingnto the current sumtyields exactly half of the total. If true, the function can immediately confirm a valid partition and exit. -
The condition
2 * (n + t) < totalensures that only sums that are still less than half of the total are retained for future expansion. Sums that would exceed half are discarded because they can never lead to a balanced partition.
After processing all reachable sums for the current number, todo is replaced by next, ready for the next iteration.
Final result
return False
If the loop completes without triggering the early return, no subset achieving half of the total was found, and the function correctly reports that partitioning is impossible.
Edge Cases Handled
When the input list is empty, total becomes 0. The initial todo set contains 0, and the outer loop does not execute. The function reaches the final return False, which is appropriate because an empty list cannot be partitioned into two non-empty subsets with equal sum.
If the total sum is odd, the condition 2 * (n + t) == total can never be satisfied because the left side is always even. Consequently, the algorithm will exhaust all possibilities and return False, correctly handling the impossibility of splitting an odd total into two equal integers.
When a single element equals half of the total (for example, [5,5]), the check 2 * (n + t) == total becomes true on the first iteration where t is 0 and n is 5. The function returns True without processing the remaining elements, demonstrating correct early termination for minimal valid partitions.
The condition 2 * (n + t) < total prevents the set from growing with sums that already exceed the target, which implicitly handles cases where large numbers would otherwise cause unnecessary growth of the reachable-sum set.
Performance Optimisations
The algorithm uses a set to store reachable sums, providing O(1) average-time membership checks and insertions. By discarding any sum that would make 2 * (n + t) >= total (except the exact equality case), it limits the size of the set to only those sums that are strictly less than half of the total. This pruning reduces both memory usage and the number of iterations in subsequent loops.
The early return on exact equality eliminates the need to continue scanning the remaining numbers once a valid partition is identified. This short-circuiting can dramatically cut runtime for inputs where a solution appears early in the sequence.
Finally, the algorithm reassigns todo to a freshly created next set each outer iteration, allowing Python’s garbage collector to reclaim the previous set’s memory promptly, which helps keep the memory footprint bounded throughout execution.
ELI5 - Simplified Explanation
Imagine you have a big pile of colorful blocks and you want to see if you can split them into two separate piles that have exactly the same amount of weight. First, the code adds up all the numbers in the pile to see how many blocks there are in total. If the total is an odd number, it is impossible to split them perfectly, but the code checks anyway. It starts by keeping a list of all the different sums that can be made using the blocks discovered so far. Inside the loop, it looks at each new block one by one. For every sum that was already possible, it explores two choices. It keeps the old sum, and it also tries adding the new block to that sum to create a brand new total. If this new total is exactly half of the big pile, that means the blocks are balanced perfectly. The process goes through every block in the pile to see if a fair split can happen anywhere along the way.
Code Quality
Complexity Analysis
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 | JS | Rust | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| bujosa | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| fsq | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| Shamik07 | Dart | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| bujosa | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| fsq | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| Shamik07 | Dart | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 698: Partition to K Equal Sum Subsets
- problem 1981: Minimize the Difference Between Target and Chosen Elements
- problem 2025: Maximum Number of Ways to Partition an Array
- problem 2035: Partition Array Into Two Arrays to Minimize Sum Difference
- problem 2395: Find Subarrays With Equal Sum
- problem 2518: Number of Great Partitions
- problem 2578: Split With Minimum Sum
Solved On The Same Day
- problem 292: Nim Game
- problem 572: Subtree of Another Tree
- problem 617: Merge Two Binary Trees
- problem 671: Second Minimum Node In a Binary Tree
- problem 152: Maximum Product Subarray
- problem 207: Course Schedule
- problem 210: Course Schedule II
- problem 211: Design Add and Search Words Data Structure
- problem 213: House Robber II
- problem 237: Delete Node in a Linked List
- problem 260: Single Number III
- problem 437: Path Sum III
- problem 450: Delete Node in a BST
- problem 560: Subarray Sum Equals K
- problem 606: Construct String from Binary Tree
- problem 623: Add One Row to Tree
- problem 652: Find Duplicate Subtrees
- problem 654: Maximum Binary Tree
- problem 655: Print Binary Tree
- problem 662: Maximum Width of Binary Tree
- problem 669: Trim a Binary Search Tree
- problem 687: Longest Univalue Path
- problem 1115: Print FooBar Alternately
- problem 1116: Print Zero Even Odd
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