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
Partition Array [4,3,2,3,5,2,1] into k=4 Equal Sum Subsets4323521Total: 20, Target per subset: 20÷4 = 5Subset 1[5]Sum: 5Subset 2[4,1]Sum: 5Subset 3[3,2]Sum: 5Subset 4[3,2]Sum: 5Result: true - All subsets have equal sum 5
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
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
125.0K Views
Medium-High Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen