Problem 416

Abstract / Summary

Check if the array can be split into two subsets with equal sums by determining if a subset sums to half the total.

Note

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

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
16 lines | 437 bytes | submitted September 4, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
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 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 including n.

  • The condition 2 * (n + t) == total checks whether adding n to the current sum t yields exactly half of the total. If true, the function can immediately confirm a valid partition and exit.

  • The condition 2 * (n + t) < total ensures 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.

written by openai gpt

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.

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 | μ = 6.70 | σ = 1.49

Complexity Analysis

not analyzed yet

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 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++
52 links | 36 authors | 11 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

7 similar problems

Solved On The Same Day

4 easy 20 medium
25 solutions   September 4, 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