← DSA Atlas
Dedicated problem page · #698

Partition to K Equal Sum Subsets

MediumBacktrackingk equal-sum subsets backtracking with used mask and pruningBacktracking filling k buckets to a target sum
Solve on LeetCode ↗
698
MediumBacktrackingBacktracking filling k buckets to a target sumk equal-sum subsets backtracking with used mask and pruning

Partition to K Equal Sum Subsets

Given an integer array nums and an integer k, determine whether it is possible to divide the array into k non-empty subsets whose sums are all equal.

Open official problem prompt ↗
In plain English

Decide whether all elements can be partitioned into k groups that each add up to total/k.

Picture it like this

Like dealing cards into k piles so every pile has the same point total; you fill one pile to the goal, then move on to the next, backtracking whenever a pile cannot be completed.

Example
Input
nums = [4,3,2,3,5,2,1], k = 4
Output
true
Why
The total is 20, so each subset must sum to 5: (5), (1,4), (2,3), and (2,3) are four equal-sum subsets using every element.
Constraints
1 <= k <= nums.length <= 161 <= nums[i] <= 10^4The sum of all nums does not exceed 2^31 - 1
Pattern lesson

See the pattern, then code

k equal-sum subsets backtracking with used mask and pruning
Recognition clue

Splitting an array into k groups of equal sum generalizes the 4-sides problem; the target per subset is total/k, and you fill one subset at a time with backtracking.

Backtracking

Generate every valid combination, permutation, partition, or configuration.. Sort descending, fill one subset up to the target, and when it is exactly full recurse to build the next subset, using a used array and start index to avoid re-picking and reordering.

New words, made simpleKnow these before the algorithm
Target sum
total/k, the required sum of each of the k subsets.
used array
Booleans marking which elements are already committed to a subset.
Subset completion
Reaching cur_sum == target, which locks a subset and starts the next one.
Approaches from first idea to best ideaCompare the trade-offs
ApproachHow it thinksCost
Enumerate all subset assignments

Explodes combinatorially and repeats symmetric group orderings.

Assign each element to one of k groups and verify equal sums.

Time O(k^n)Space O(n)
The rule we keep true

Invariant

Elements marked used belong to already-completed or in-progress subsets; cur_sum is the running sum of the subset currently being built and never exceeds target.

Why this is correct

Reasoning

Each completed subset sums to exactly target, and completing k of them consumes all elements because k*target equals the total. Filling subsets one at a time with a start index avoids duplicate orderings, and skipping overflowing elements keeps every subset valid.

The algorithm in three movesSay these aloud before coding
1Return false unless total is divisible by k and max element fits the target

target = 20/4 = 5

2Sort descending and track a used flag per element

subset1={5}, subset2={4,1}

3Add unused elements from a start index without exceeding the target

subset3={3,2}, subset4={3,2} -> true

4When cur_sum hits target, decrement k and restart from index 0 for the next subset

5Prune symmetric branches when cur_sum is 0 and a placement fails

Visual trace

Follow the data, one decision at a time

Input snapshotHighlighted cells are involved in this example
50
41
32
33
24
25
16
1 · Read[4,3,2,3,5,2,1], k=4
2 · AskDivisible by k? Max fits?
3 · Update statetotal=20, target=5, sorted=[5,4,3,3,2,2,1]
4 · ResultProceed
Key takeaway

Elements sorted descending; the lone 5 immediately forms one complete subset.

Code walkthrough

Read the solution in small chunks

Python 3

Do not memorize the whole program. Connect each group of lines to one job in the algorithm.

  1. 1
    Lines 3-9Feasibility and sort

    Reject non-divisible totals or an oversized element; sort descending so large elements are placed first.

  2. 2
    Lines 12-15Subset boundaries

    k_remaining==0 means success; a full subset resets cur_sum and starts the next subset from index 0.

  3. 3
    Lines 16-25Pick with pruning

    Skip used or overflowing elements; on failure undo, and break when cur_sum is 0 to prune symmetric starts.

Make it stick

Edge cases, mistakes, and one self-check

E

Edge cases to test

  • k equal to nums.length requires every element to equal the target
  • Total not divisible by k returns false
  • Any single element exceeding target returns false
  • k == 1 always true since the whole array is one subset
!

Common beginner mistakes

  • Recursing from i instead of i+1, reusing an element within a subset
  • Not resetting start to 0 when a subset completes
  • Omitting the cur_sum==0 break, losing a major prune
  • Forgetting to mark and unmark used, corrupting other branches
Check your understanding

Why restart the next subset from index 0 rather than continuing from the current index?