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 to K Equal Sum Subsets INPUT nums array: 4 3 2 3 5 2 1 0 1 2 3 4 5 6 nums = [4,3,2,3,5,2,1] k = 4 Total sum = 20 Target sum per subset: 20 / 4 = 5 Sorted: [5,4,3,3,2,2,1] (descending for pruning) ALGORITHM STEPS 1 Validate Input Check: sum % k == 0 20 % 4 = 0 (OK) 2 Sort Descending Start with largest Prune early failures 3 Backtrack Search Try placing each num in k buckets 4 Check Bucket Sum Each bucket must = 5 Skip if exceeds target Bucket States: [5] sum=5 [4,1] sum=5 [3,2] sum=5 [3,2] sum=5 All buckets = target! FINAL RESULT 4 Equal Subsets Found: Subset 1: 5 = 5 OK Subset 2: 4 1 = 5 OK Subset 3: 3 2 = 5 OK Subset 4: 3 2 = 5 OK Output: true Key Insight: Use backtracking with k buckets. Sort array in descending order to fail fast - larger numbers are harder to place. Skip duplicate bucket states to avoid redundant work. Prune when bucket sum exceeds target. Time: O(k * 2^n), Space: O(n) for recursion stack and bucket array. TutorialsPoint - Partition to K Equal Sum Subsets | Backtracking with Pruning
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