## Three Partition Problem in JavaIt is very interesting problem frequently asked in interviews of top IT companies like ## Problem StatementAn array of non-negative numbers is given. Our task is to check whether the input array can be partitioned into the three completely disjoint subsets or not, such that the sum of all the elements of one subset is equal to the sum of all the elements of the other subset. Note that all the elements of the input array have to be included. Display appropriate messages on the console accordingly.
int inputArr[] = {3, 7, 1, 2, 4, 5, 8}
Subset1 = {3, 7} sum = 3 + 7 = 1=, Subset2 = {1, 4, 5} sum = 1 + 4 + 5 = 10, Subset3 = {2, 8} sum = 2 + 8 = 10 Thus, we see that we got the three subsets of an equal sum of elements.
int inputArr[] = {6, 2, 3, 9, 8, 18, 96}
## Approach: Using RecursionFirst of all, we will check whether the sum of all the elements of the input array is a multiple of 3 or not. If it is not the multiple of 3, then it is not possible to do the partition. If yes, then we have to check whether three disjoint sets exist or not whose sum of elements is equal to (total sum of elements of the input array) / 3 or not. It can be found by considering each element of the input array one by one. For every element, there are the following three possibilities: 1) Consider the element for the first subset, and apply recursion for the other elements. 2) Consider the element for the second subset, and apply recursion for the other elements. 3) Consider the element for the third subset, and apply recursion for the other elements.
For the input array: 3 7 1 2 4 5 8 It is possible to partition it into three disjoint subsets. For the input array: 6 2 3 9 8 18 96 It is not possible to partition it into three disjoint subsets.
The above program gives the correct output but will consume a lot of time giving the output. Thus, it is not suitable to handle an input of a large size. ## Approach: Using Dynamic ProgrammingTo reduce the time complexity, we can take the help of dynamic programming. Observe the following program.
For the input array: 3 7 1 2 4 5 8 It is possible to partition it into three disjoint subsets. For the input array: 6 2 3 9 8 18 96 It is not possible to partition it into three disjoint subsets.
## Extension to The ProblemAnother thing that can be asked by an interviewer is to print those three disjoint subsets whose sum is equal. For that, an array will be required to keep track of all the disjoint subset elements. Observe the following program.
For the input array: 3 7 1 2 4 5 8 It is possible to partition it into three disjoint subsets. Partition 0 is 2 8 Partition 1 is 1 4 5 Partition 2 is 3 7 For the input array: 6 2 3 9 8 18 96 It is not possible to partition it into three disjoint subsets. |

For Videos Join Our Youtube Channel: Join Now

- Send your Feedback to [email protected]