Problem 698

Abstract / Summary

Determine if a list of integers can be divided into k groups that each have the same total sum.

Note

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

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, [])
37 lines | 1050 bytes | submitted May 19, 2024 | GitHub   10% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 39% (900k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Bit Manipulation
  • Bitmask
  • Dynamic Programming
  • Memoization
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 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 False immediately, 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., k becomes zero) is recognized as a successful partition, returning True.
  • 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 % k and max(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] += n followed by have[i] -= n) avoids the overhead of copying the entire have list 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.

written by openai gpt

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.

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 = 6 | μ = 6.41 | σ = 1.31

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 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++
34 links | 20 authors | 8 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

1 medium
2 solutions   May 19, 2024

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