Partition to K Equal Sum Subsets — LeetCode 698 Python Solution

MediumBit ManipulationMemoizationArrayDynamic ProgrammingBacktrackingBitmask
Problem
#698
Reading time
4 min

The problem

Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.

Example

Input
nums = [4,3,2,3,5,2,1], k = 4
Output
true
Explanation
It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.

Python solution

Python
class Solution:
    def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
        def dfs(i: int) -> bool:
            if i == len(nums):
                return True
            for j in range(k):
                if j and cur[j] == cur[j - 1]:
                    continue
                cur[j] += nums[i]
                if cur[j] <= s and dfs(i + 1):
                    return True
                cur[j] -= nums[i]
            return False

        s, mod = divmod(sum(nums), k)
        if mod:
            return False
        cur = [0] * k
        nums.sort(reverse=True)
        return dfs(0)

Complexity

MeasureComplexity
TimeO(n \times 2^n)
SpaceO(2^n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 698. Partition to K Equal Sum Subsets is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 698. Partition to K Equal Sum Subsets?
LeetCode 698. Partition to K Equal Sum Subsets is rated Medium on LeetCode.
What is the time complexity of LeetCode 698. Partition to K Equal Sum Subsets?
The Python solution on this page runs in O(n \times 2^n).
What is the space complexity of LeetCode 698. Partition to K Equal Sum Subsets?
The Python solution on this page uses O(2^n) auxiliary space.
What topics does LeetCode 698. Partition to K Equal Sum Subsets cover?
LeetCode 698. Partition to K Equal Sum Subsets is tagged Bit Manipulation, Memoization, Array, Dynamic Programming, Backtracking and Bitmask on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview