Partition to K Equal Sum Subsets

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.

30:00

Partition to K Equal Sum Subsets
medium
Free written solution
Topics
Companies

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.

Example 1:
Input: {"nums":[4,3,2,3,5,2,1],"k":4}
Output: true
Constraints:
  • 1≤k≤nums.length≤161 \leq k \leq nums.length \leq 16

  • 1≤nums[i]≤1041 \leq nums[i] \leq 10^4

  • The frequency of each element is in the range [1,4][1, 4].

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[4,3,2,3,5,2,1],"k":4}

We need 4 groups with equal sums. First add everything up.

numbers

total = 20

4
i0
3
i1
2
i2
3
i3
5
i4
2
i5
1
i6

4 buckets, each must reach exactly ?

backtracks = 0

0/?

b0

0/?

b1

0/?

b2

0/?

b3

green dash = fits

red dash = would overflow

orange = just undone

dashed line = target

Variables
VariableValue
k4
DepthFunction Call
Stack empty
0/32