What is "Subset Sum Problem" ?

Posted by on Mar 31, 2024

Given an integer array "arr" of size "n" and an integer "sum", the task is to find whether there exists a subset in "arr" whose sum equals "sum".

If such a subset exists, return "true," otherwise return "false."

Input: arr[] = {3, 34, 4, 12, 5, 2}, sum = 9
Output: true
Possible subsets are: {3, 4, 2}, {4,5}

Input: arr[] = {3, 34, 4, 12, 5, 2}, sum = 30
Output: false


Solutions

Method 1: Memoization

The Memoization Technique is basically an extension to the recursive approach so that we can overcome the problem of calculating redundant cases and thus decrease time complexity.

We can see that in each recursive call only the value of "n" and "sum" changes, so we can store and reuse the result of a function(..n, sum..) call using a "n * sum" 2-D array.

The 2-D array will store a particular state (n, sum) if we get it the first time.

Now, if we come across the same state (n, w) again, instead of calculating it in exponential complexity, we can directly return its result stored in the table in constant time.

Complexity

The time complexity of this solution is (n * sum).

In addition, O(n * w) auxiliary space was used by the table and O(n) by call stack.

Method 2: Recursion

The idea of the recursive approach is to consider all subsets of items and find whether there exists a subset whose sum equals "sum".

While considering an item, we have one of the following two choices:

Choice 1: The item is included in the optimal subset—decrease the sum by the item value.
Choice 2: The item is not included in the optimal set—don't do anything.

While picking an element, also make sure that the value of the item is less than or equal to the remaining "sum".

If sum is exhausted (equals to "0"), then return "true" and if array is exhausted (n equals to "0"), return "false".

Complexity

The above recursive function computes the same sub-problems again and again.

The time complexity of this solution is exponential (2^n).

In addition, O(N) auxiliary stack space was used for the recursion stack.

Related


Count number of subsets with given sum

Longest Common Subsequence (LCS)

Minimum number of deletions and insertions

Print Shortest Common Super-sequence (SCS)

Equal subset sum partition problem

What is the "Rod Cutting Problem" ?

Print Longest Common Subsequence (LCS)

Unbounded knapsack (Recursion & Dynamic Programming)

Find length of the Longest Common Substring

Shortest Common Super-sequence (SCS)