Given an array of positive integers, which can be partitioned into three disjoint subsets having the same sum, print the partitions.

For example, consider the following set:

S = { 7, 3, 2, 1, 5, 4, 8 }

We can partition S into three partitions, each having a sum of 10.

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

Practice this problem

As discussed in the previous post, the 3–partition problem is a special case of the Partition Problem. The goal is to partition S into 3 subsets with an equal sum, unlike the partition problem, where the goal is to partition S into two subsets with an equal sum.

This post will extend the previous solution to print the partitions. The idea is to maintain a separate array A[] to keep track of subsets elements. The implementation can be seen below in C++, Java, and Python. Note that if the value of A[i] is k, it means that the i'th item of S is part of the k'th subset.

C++


Download  Run Code

Output:

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

Java


Download  Run Code

Output:

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

Python


Download  Run Code

Output:

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

The time complexity of the above solution is exponential and occupies space in the call stack. It can be optimized using dynamic programming, as discussed in the previous post.

 
Exercise: Extend the solution to print k–partitions