In the k–partition problem, we need to partition an array of positive integers into k disjoint subsets that all have an equal sum, and they completely cover the set.

For example, consider set S = { 7, 3, 5, 12, 2, 1, 5, 3, 8, 4, 6, 4 }.

 
1. S can be partitioned into two partitions, each having a sum of 30.

S1 = { 5, 3, 8, 4, 6, 4 }
S2 = { 7, 3, 5, 12, 2, 1 }

2. S can be partitioned into three partitions, each having a sum of 20.

S1 = { 2, 1, 3, 4, 6, 4 }
S2 = { 7, 5, 8 }
S3 = { 3, 5, 12 }

3. S can be partitioned into four partitions, each having a sum of 15.

S1 = { 1, 4, 6, 4 }
S2 = { 2, 5, 8 }
S3 = { 12, 3 }
S4 = { 7, 3, 5 }

4. S can be partitioned into five partitions, each having a sum of 12.

S1 = { 2, 6, 4 }
S2 = { 8, 4 }
S3 = { 3, 1, 5, 3 }
S4 = { 12 }
S5 = { 7, 5 }

 

Practice this problem

 
k-partition problem is a special case of Partition Problem, where the goal is to partition S into two subsets with equal sum. This post will extend the 3-partition solution to find and print k–partitions.

We can start by calculating the sum of all elements in the set. If the sum is not divisible by k, we can’t divide the array into k subsets with an equal sum. If the sum is divisible by k, check if k subsets with the sum of elements equal to sum/k exists or not. We can find this by considering each item in the given array one by one, and for each item, include it in the i'th subset & recur for the remaining items with the remaining sum. We backtrack if the solution is not found by including a current item in the i'th subset and try for the (i+i)'th subset.

The solution should return true and print the subsets when k subsets each with zero-sum are found. For printing the partitions, maintain a separate array A[] to keep track of subsets elements. If the value of A[i] is k, then it means that the i'th item of S is part of the k'th subset.

 
The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Partition 0 is 2 6 4
Partition 1 is 8 4
Partition 2 is 3 1 5 3
Partition 3 is 12
Partition 4 is 7 5

Java


Download  Run Code

Output:

Partition 0 is 2 6 4
Partition 1 is 8 4
Partition 2 is 3 1 5 3
Partition 3 is 12
Partition 4 is 7 5

Python


Download  Run Code

Output:

Partition 0 is [2, 6, 4]
Partition 1 is [8, 4]
Partition 2 is [3, 1, 5, 3]
Partition 3 is [12]
Partition 4 is [7, 5]

The time complexity of the above solution is exponential and requires additional space for the recursion (call stack).