# Partition problem | Dynamic Programming Solution

Given a set of positive integers, find if it can be divided into two subsets with equal sum.

For example,

S = {3,1,1,2,2,1},

We can partition S into two partitions each having sum 5.

S1 = {1,1,1,2}
S2 = {2,3}.

Note that this solution is not unique. Below is another solution.

S1 = {3,1,1}
S2 = {2,2,1}

Partition problem is special case of Subset Sum Problem which itself is a special case of the Knapsack Problem. The idea is to calculate sum of all elements in the set. If sum is odd, we can’t divide the array into two sets. If sum is even, we check if subset with sum/2 exists or not. Below is the algorithm to find subset sum –

We consider each item in the given array one by one and for each item, there are two possibilities –

1. We include current item in the subset and recurse for remaining items with remaining sum.

2. We exclude current item from subset and recurse for remaining items.

Finally, we return true if we get subset by including or excluding current item else we return false. The base case of the recursion would be when no items are left or sum becomes negative. We return true when sum becomes 0 i.e. subset is found.

Output:

Yes

## Java

Output:

Yes

The time complexity of above solution is exponential and auxiliary space used by the program is O(1).

The problem has an optimal substructure and it also exhibits overlapping subproblems i.e. the problem can be split into smaller subproblems and same subproblems will get computed again and again. We can easily prove this by drawing a recurion tree of above code.

We can use Dynamic Programming to solve this problem by saving subproblem solutions in memory rather than computing them again and again. We solve smaller sub-problems first, then solve larger sub-problems from them. The following bottom-up approach computes T[i][j], for each 1 <= i <= n and 1 <= j <= sum, which is true if subset with sum j can be found using items up to first i items. It uses value of smaller values i and j already computed. It has the same asymptotic run-time as Memoization but no recursion overhead.

Output:

Yes

## Java

Output:

Yes

The time complexity of above solution is O(n x sum) where sum is sum of all elements in the array. Auxiliary space used by the program is also O(n x sum).

Exercise: Extend the solution to 3-partitions and also print the partitions.

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Get great deals at Amazon

Subscribe
Notify of