πDay 14. Subset Sum Problem π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given an array of positive integers arr[] and a target value sum, determine if there exists a subset of arr[]
whose sum is exactly equal to the given sum.
π Example Walkthrough:
Example 1:
Input:
arr[] = {3, 34, 4, 12, 5, 2}
sum = 9
Output:
true
Explanation:
A subset {4, 3, 2}
exists with sum = 9.
Example 2:
Input:
arr[] = {3, 34, 4, 12, 5, 2}
sum = 30
Output:
false
Explanation:
There is no subset with sum = 30.
Example 3:
Input:
arr[] = {1, 2, 3}
sum = 6
Output:
true
Explanation:
The entire array {1, 2, 3}
forms the subset with sum = 6.
Constraints:
$1 \leq \text{size of arr} \leq 200$
$1 \leq arr[i] \leq 200$
$1 \leq sum \leq 10^4$
π― My Approach:
Dynamic Programming (Optimized 1D DP) β O(N Γ sum) Time, O(sum) Space
Define a boolean DP array
dp[sum + 1]
, wheredp[j]
tells whether sumj
is possible.Base Case:
dp[0] = true
(sum 0 is always achievable).Iterate through each number in the array and update
dp[j]
for allj
fromsum
down tonum
.Transition Formula: $[ \text{dp}[j] = \text{dp}[j] \ OR\ \text{dp}[j - \text{num}] $]
If
dp[j - num]
wastrue
, thendp[j]
can also becometrue
by includingnum
.
Return
dp[sum]
as the final answer.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(N Γ sum), since we iterate through all elements and update the DP table.
Expected Auxiliary Space Complexity: O(sum), as we use a 1D array of size
sum + 1
.
π Solution Code
Code (C++)
class Solution {
public:
bool isSubsetSum(vector<int>& arr, int sum) {
vector<bool> dp(sum + 1, false);
dp[0] = true;
for (int num : arr)
for (int j = sum; j >= num; --j)
dp[j] = dp[j] || dp[j - num];
return dp[sum];
}
};
Code (Java)
class Solution {
static boolean isSubsetSum(int[] arr, int sum) {
boolean[] dp = new boolean[sum + 1];
dp[0] = true;
for (int num : arr)
for (int j = sum; j >= num; --j)
dp[j] |= dp[j - num];
return dp[sum];
}
}
Code (Python)
class Solution:
def isSubsetSum(self, arr, sum):
dp = [False] * (sum + 1)
dp[0] = True
for num in arr:
for j in range(sum, num - 1, -1):
dp[j] |= dp[j - num]
return dp[sum]
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated