Partition to K Equal Sum Subsets - Problem

Imagine you have a collection of numbered cards and want to distribute them into k equal-value piles. This is exactly what the Partition to K Equal Sum Subsets problem asks you to solve!

Given an integer array nums and an integer k, your task is to determine if it's possible to divide the array into k non-empty subsets where each subset has the exact same sum.

Key Requirements:

  • All k subsets must be non-empty
  • Every element must belong to exactly one subset
  • All subset sums must be equal

Example: If nums = [4,3,2,3,5,2,1] and k = 4, we can form 4 subsets: [5], [1,4], [2,3], [2,3] - each with sum 5!

Input & Output

example_1.py โ€” Basic Partition
$ Input: nums = [4,3,2,3,5,2,1], k = 4
โ€บ Output: true
๐Ÿ’ก Note: We can form 4 subsets with equal sum 5: [5], [1,4], [2,3], [2,3]. Each subset sums to 5.
example_2.py โ€” Impossible Partition
$ Input: nums = [1,2,3,4], k = 3
โ€บ Output: false
๐Ÿ’ก Note: Total sum is 10, which cannot be evenly divided into 3 subsets (10/3 is not an integer).
example_3.py โ€” Single Element Subsets
$ Input: nums = [2,2,2,2,2,2], k = 3
โ€บ Output: true
๐Ÿ’ก Note: We can form 3 subsets: [2,2], [2,2], [2,2]. Each subset has sum 4.

Visualization

Tap to expand
๐Ÿดโ€โ˜ ๏ธ Pirate Treasure Distribution ๐Ÿดโ€โ˜ ๏ธTreasure Chest: [5, 4, 3, 3, 2, 2, 1]54332214 Pirate Crews (k=4, target sum=5 each)Crew 15Sum: 5 โœ“Crew 241Sum: 5 โœ“Crew 332Sum: 5 โœ“Crew 432Sum: 5 โœ“โšก SUCCESS! All crews have equal treasure โšก
Understanding the Visualization
1
Check Feasibility
Verify total treasure can be divided equally among k crews
2
Sort by Value
Start with most valuable coins to fail fast if impossible
3
Distribute Recursively
Try assigning each coin to crews that can accommodate it
4
Prune Invalid Paths
Skip equivalent empty crews and impossible assignments
Key Takeaway
๐ŸŽฏ Key Insight: Sort elements in descending order and use backtracking with pruning to efficiently explore the solution space. Memoization with bitmasks can further optimize by avoiding redundant state calculations.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(k^n)

Worst case is still exponential, but pruning significantly reduces average case

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Recursion stack depth plus array for subset sums

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค k โ‰ค nums.length โ‰ค 16
  • 1 โ‰ค nums[i] โ‰ค 104
  • Small input size allows for exponential algorithms
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
127.8K Views
Medium-High Frequency
~25 min Avg. Time
3.2K 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