#698

Partition to K Equal Sum Subsets

Medium
ArrayDynamic ProgrammingBacktrackingBit ManipulationMemoizationBitmaskBacktrackingMemoizationDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * 2^n)
Space
O(1)
O(n)
💡

Intuition

Time O(n * 2^n)Space O(n)

The optimal solution uses backtracking with memoization to efficiently explore valid combinations of subsets. This significantly reduces the number of recursive calls by avoiding repeated calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the total sum and check if it can be divided by k.
  2. 2Step 2: Sort the array in descending order to optimize the backtracking process.
  3. 3Step 3: Use a recursive function with memoization to try to fill each subset while keeping track of the current index and the current subset sums.
solution.py25 lines
1# Full working Python code
2from functools import lru_cache
3
4def canPartitionKSubsets(nums, k):
5    total_sum = sum(nums)
6    if total_sum % k != 0:
7        return False
8    target = total_sum // k
9    nums.sort(reverse=True)
10
11    @lru_cache(None)
12    def backtrack(index, subset_sums):
13        if index == len(nums):
14            return all(s == target for s in subset_sums)
15        for i in range(k):
16            if subset_sums[i] + nums[index] <= target:
17                subset_sums[i] += nums[index]
18                if backtrack(index + 1, tuple(subset_sums)):
19                    return True
20                subset_sums[i] -= nums[index]
21            if subset_sums[i] == 0:
22                break
23        return False
24
25    return backtrack(0, tuple([0] * k))

Complexity note: The time complexity is O(n * 2^n) due to the recursive nature of the backtracking with memoization. The space complexity is O(n) for the recursion stack and the memoization storage.

  • 1The total sum must be divisible by k to form equal subsets.
  • 2Sorting the array helps in optimizing the backtracking process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.