Python 0698.py
class Solution:
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
total = sum(nums)
if total % k != 0:
return False
# sum of every partition
need = total // k
if max(nums) > need:
return False
nums.sort(reverse = True)
while nums and nums[0] == need:
nums.pop(0)
k -= 1
if k == 0:
return True
def deeper(pos, have):
if pos == len(nums):
return min(have) == need
# try to add current number to an existing set
n = nums[pos]
for i in range(len(have)):
have[i] += n
if have[i] <= need:
if deeper(pos + 1, have):
return True
have[i] -= n
# start new set
if len(have) == k:
return False
return deeper(pos + 1, have + [ n ])
return deeper(0, [])
Difficulty
and has an acceptance rate of about 39% (900k+ submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
- Bit Manipulation
- Bitmask
- Dynamic Programming
- Memoization
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 an array of positive integers can be divided into k subsets whose sums are all equal. It first validates basic feasibility conditions, then reduces the problem size by removing elements that already form a complete subset. The core of the algorithm is a depth-first search (deeper) that attempts to assign each remaining number to an existing partial subset or to start a new subset, backtracking when a placement violates the target sum.
Key Steps
The function begins by computing the total sum of the input list and checks whether it is divisible by k. This early exit prevents unnecessary work when an equal partition is mathematically impossible.
total = sum(nums)
if total % k != 0:
return False
The required sum for each subset, need, is derived from the total. A second feasibility check ensures that no single element exceeds this target, because such an element could never belong to a valid subset.
need = total // k
if max(nums) > need:
return False
Sorting the numbers in descending order improves the efficiency of the subsequent search. Larger numbers are placed first, which quickly prunes branches that would exceed need.
nums.sort(reverse=True)
Elements that already equal the target sum are removed from the list, and the corresponding subset count is decremented. This step reduces the depth of recursion and the size of the state space.
while nums and nums[0] == need:
nums.pop(0)
k -= 1
if k == 0:
return True
The recursive helper deeper receives the current position in the sorted list and a list have that records the accumulated sums of the subsets built so far. When all numbers have been processed, the function verifies that every accumulated sum matches the target.
def deeper(pos, have):
if pos == len(nums):
return min(have) == need
For each number, the algorithm first attempts to add it to each existing subset, checking that the addition does not exceed need. If a placement is viable, the recursion proceeds; otherwise the change is undone (backtracking).
n = nums[pos]
for i in range(len(have)):
have[i] += n
if have[i] <= need:
if deeper(pos + 1, have):
return True
have[i] -= n
If the number cannot be placed in any existing subset, the algorithm tries to start a new subset, provided the current number of subsets is still less than k. The new subset is represented by appending the current number to have.
if len(have) == k:
return False
return deeper(pos + 1, have + [n])
The initial call starts the recursion with an empty have list.
return deeper(0, [])
Edge Cases Handled
The code explicitly addresses several boundary conditions:
- When the total sum is not divisible by k, the function returns
Falseimmediately, covering cases where an equal partition is impossible. - If any element exceeds the required subset sum, the function returns
False, handling inputs where a single large number prevents any valid grouping. - Elements that are exactly equal to the target sum are removed before recursion, which correctly deals with inputs containing numbers that already form complete subsets.
- The situation where all numbers are removed by the previous step (i.e.,
kbecomes zero) is recognized as a successful partition, returningTrue. - The recursion base case checks that every built subset reaches the target sum, ensuring that partial solutions that leave any subset incomplete are rejected.
Performance Optimizations
Several design choices contribute to a more efficient search:
- Early feasibility checks (
total % kandmax(nums) > need) eliminate impossible instances without entering the recursive phase. - Descending sort places larger numbers first, causing early detection of over-flows and reducing the number of recursive calls.
- Pre-removal of exact matches shrinks the problem size, decreasing both the depth of recursion and the branching factor.
- Backtracking with in-place updates (
have[i] += nfollowed byhave[i] -= n) avoids the overhead of copying the entirehavelist for each trial placement, limiting memory allocation to the occasional creation of a new subset (have + [n]). - Limiting new subset creation to when the current number of subsets is less than k prevents unnecessary exploration of configurations that would exceed the allowed subset count.
These optimizations collectively reduce the exponential search space typical of partitioning problems, allowing the algorithm to solve moderate-size inputs within practical time limits.
ELI5 - Simplified Explanation
Imagine having a big pile of cookies and a bunch of empty plates. The goal is to put all the cookies onto the plates so that every plate has exactly the same amount of sweetness.
First, the code checks if the total number of cookies can even be shared equally among the plates. If the cookies do not add up to a number that divides perfectly by the number of plates, it is impossible to finish the puzzle. Also, if even one single cookie is bigger than what an entire plate is allowed to hold, the task cannot be done.
To make things easier, the cookies are sorted from the biggest to the smallest. This helps because dealing with the big, bulky cookies first usually makes the rest of the work proceed much faster.
The computer then starts a little adventure to try different combinations. It picks up a cookie and looks for a plate where it fits without making the plate hold too many cookies. If a cookie fits, it stays there and the computer moves to the next cookie. If the current plan does not work out, it takes the cookie back off the plate and tries putting it on a different plate instead. This is like trying every possible way to arrange the cookies until everything is perfectly balanced. If the computer tries every possibility and still cannot make the plates equal, it knows for sure that the goal cannot be reached.
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 | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| MemoryLimitExceeded | C++ | Python | |||||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| FelixFan1122 | C# | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| sonugiri1043 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| FelixFan1122 | C# | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| sonugiri1043 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 416: Partition Equal Subset Sum
- problem 2025: Maximum Number of Ways to Partition an Array
Solved On The Same Day
- problem 756: Pyramid Transition Matrix
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