Partition to K Equal Sum Subsets - 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.
Each element in the array must belong to exactly one subset, and all subsets must have the same sum.
Note: The order of elements within subsets does not matter, only that each subset has equal sum.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [4,3,2,3,5,2,1], k = 4
›
Output:
true
💡 Note:
Can form 4 subsets with sum 5 each: [5], [4,1], [3,2], [3,2]. Total sum 20 ÷ 4 = 5 per subset.
Example 2 — Impossible Case
$
Input:
nums = [1,2,3,4], k = 3
›
Output:
false
💡 Note:
Total sum is 10, which is not divisible by 3. Cannot form 3 equal-sum subsets.
Example 3 — Single Element
$
Input:
nums = [2,2,2,2,3,3], k = 2
›
Output:
true
💡 Note:
Can form 2 subsets with sum 7 each: [2,2,3] and [2,2,3]. Each subset sums to 7.
Constraints
- 1 ≤ k ≤ nums.length ≤ 16
- 1 ≤ nums[i] ≤ 104
- The frequency of each element is in the range [1, 4]
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [4,3,2,3,5,2,1] and k=4 subsets needed
2
Check
Total sum 20 ÷ 4 = 5, so each subset needs sum 5
3
Partition
Found valid partition: [5], [4,1], [3,2], [3,2]
Key Takeaway
🎯 Key Insight: First check if total sum is divisible by k, then use backtracking with pruning to find valid partitions
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code