Given an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum.
Examples:
Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 9
Output: True
Explanation: There is a subset (4, 5) with sum 9.
Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 30
Output: False
Explanation: There is no subset that add up to 30.
[Naive Approach] Using Recursion – O(2^n) Time and O(n) Space
For the recursive approach, there will be two cases (In both cases, the number of available elements decreases by 1)
- Consider the 'last' element to be a part of the subset. Now the new required sum = required sum - value of 'last' element.
- Don't include the 'last' element in the subset. Then the new required sum = old required sum.
Mathematically the recurrence relation will look like the following:
isSubsetSum(arr, n, sum) = isSubsetSum(arr, n-1, sum) OR isSubsetSum(arr, n-1, sum - arr[n-1])
Base Cases:
- isSubsetSum(arr, n, sum) = false, if sum > 0 and n = 0
- isSubsetSum(arr, n, sum) = true, if sum = 0
Follow the below steps to implement the recursion:
- Build a recursive function and pass the index to be considered (here gradually moving from the last end) and the remaining sum amount.
- For each index check the base cases.
- If the answer is true for any recursion call, then there exists such a subset. Otherwise, no such subset exists.
C++
//C++ implementation for subset sum
// problem using recursion
#include <bits/stdc++.h>
using namespace std;
// Function to check if there is a subset
// with the given sum using recursion
bool isSubsetSumRec(vector<int>& arr, int n, int sum) {
// Base Cases
if (sum == 0)
return true;
if (n == 0)
return false;
// If last element is greater than sum,
// then ignore it
if (arr[n - 1] > sum)
return isSubsetSumRec(arr, n - 1, sum);
// Check if sum can be obtained by including
// or excluding the last element
return isSubsetSumRec(arr, n - 1, sum)
|| isSubsetSumRec(arr, n - 1, sum - arr[n - 1]);
}
bool isSubsetSum(vector<int>& arr, int sum) {
return isSubsetSumRec(arr, arr.size(), sum);
}
int main() {
vector<int> arr = {3, 34, 4, 12, 5, 2};
int sum = 9;
if (isSubsetSum(arr, sum))
cout << "True" << endl;
else
cout << "False" << endl;
return 0;
}
C
//C implementation for subset sum
// problem using recursion
#include <stdio.h>
// Function to check if there is a subset
// with the given sum using recursion
int isSubsetSumRec(int arr[], int n, int sum) {
// Base Cases
if (sum == 0) {
return 1;
}
if (n == 0) {
return 0;
}
// If last element is greater than sum, ignore it
if (arr[n - 1] > sum) {
return isSubsetSumRec(arr, n - 1, sum);
}
// Check if sum can be obtained by including
// or excluding the last element
return isSubsetSumRec(arr, n - 1, sum) ||
isSubsetSumRec(arr, n - 1, sum - arr[n - 1]);
}
int isSubsetSum(int arr[], int n, int sum) {
return isSubsetSumRec(arr, n, sum);
}
int main() {
int arr[] = {3, 34, 4, 12, 5, 2};
int sum = 9;
int n = sizeof(arr) / sizeof(arr[0]);
if (isSubsetSum(arr, n, sum)) {
printf("True\n");
} else {
printf("False\n");
}
return 0;
}
Java
//Java implementation for subset sum
// problem using recursion
import java.util.*;
class GfG {
// Function to check if there is a subset
// with the given sum using recursion
static boolean isSubsetSumRec(int[] arr, int n, int sum) {
// Base Cases
if (sum == 0) {
return true;
}
if (n == 0) {
return false;
}
// If last element is greater than
// sum, ignore it
if (arr[n - 1] > sum) {
return isSubsetSumRec(arr, n - 1, sum);
}
// Check if sum can be obtained by including
// or excluding the last element
return isSubsetSumRec(arr, n - 1, sum) ||
isSubsetSumRec(arr, n - 1, sum - arr[n - 1]);
}
static boolean isSubsetSum(int[] arr, int sum) {
return isSubsetSumRec(arr, arr.length, sum);
}
public static void main(String[] args) {
int[] arr = {3, 34, 4, 12, 5, 2};
int sum = 9;
if (isSubsetSum(arr, sum)) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
Python
# Python implementation for subset sum
# problem using recursion
def isSubsetSumRec(arr, n, sum):
# Base Cases
if sum == 0:
return True
if n == 0:
return False
# If the last element is greater
# than the sum, ignore it
if arr[n - 1] > sum:
return isSubsetSumRec(arr, n - 1, sum)
# Check if sum can be obtained by including
# or excluding the last element
return (isSubsetSumRec(arr, n - 1, sum) or
isSubsetSumRec(arr, n - 1, sum - arr[n - 1]))
def isSubsetSum(arr, sum):
return isSubsetSumRec(arr, len(arr), sum)
if __name__ == "__main__":
arr = [3, 34, 4, 12, 5, 2]
sum = 9
if isSubsetSum(arr, sum):
print("True")
else:
print("False")
C#
// C# implementation for subset sum
// problem using recursion
using System;
class GfG {
// Function to check if there is a subset
// with the given sum using recursion
static bool isSubsetSumRec(int[] arr, int n, int sum) {
// Base Cases
if (sum == 0)
return true;
if (n == 0)
return false;
// If the last element is greater than the sum,
// ignore it
if (arr[n - 1] > sum)
return isSubsetSumRec(arr, n - 1, sum);
// Check if sum can be obtained by including
// or excluding the last element
return isSubsetSumRec(arr, n - 1, sum)
|| isSubsetSumRec(arr, n - 1, sum - arr[n - 1]);
}
static bool isSubsetSum(int[] arr, int sum) {
return isSubsetSumRec(arr, arr.Length, sum);
}
static void Main(string[] args) {
int[] arr = { 3, 34, 4, 12, 5, 2 };
int sum = 9;
if (isSubsetSum(arr, sum))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
// Javascript implementation for subset sum
// problem using recursion
function isSubsetSumRec(arr, n, sum) {
// Base Cases
if (sum === 0) return true;
if (n === 0) return false;
// If the last element is greater than
// the sum, ignore it
if (arr[n - 1] > sum) {
return isSubsetSumRec(arr, n - 1, sum);
}
// Check if sum can be obtained by including
// or excluding the last element
return isSubsetSumRec(arr, n - 1, sum) ||
isSubsetSumRec(arr, n - 1, sum - arr[n - 1]);
}
function isSubsetSum(arr, sum) {
return isSubsetSumRec(arr, arr.length, sum);
}
// Driver code
const arr = [3, 34, 4, 12, 5, 2];
const sum = 9;
if (isSubsetSum(arr, sum)) {
console.log("True");
} else {
console.log("False");
}
[Better Approach 1] Using Top-Down DP (Memoization) - O(sum*n) Time and O(sum*n) Space
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming.
1. Optimal Substructure:
The solution to the subset sum problem can be derived from the optimal solutions of smaller subproblems. Specifically, for any given n (the number of elements considered) and a target sum, we can express the recursive relation as follows:
- If the last element (arr[n-1]) is greater than sum, we cannot include it in our subset isSubsetSum(arr,n,sum) = isSubsetSum(arr,n-1,sum)
If the last element is less than or equal to sum, we have two choices:
- Include the last element in the subset, isSubsetSum(arr,n,sum) = isSubsetSum(arr,n-1,sum-arr[n−1])
- Exclude the last element, isSubsetSum(arr,n,sum) = isSubsetSum(arr,n-1,sum)
2. Overlapping Subproblems:
When implementing a recursive approach to solve the subset sum problem, we observe that many subproblems are computed multiple times. For instance, when computing isSubsetSum(arr, sum), where arr[] = {2,3,1,1} and sum = 4 we might need to compute isSubsetSum(1,3) multiple times.
Overlapping subproblems- The recursive solution involves changing two parameters: the current index in the array (n) and the current target sum (sum). We need to track both parameters, so we create a 2D array of size (n+1) x (sum+1) because the value of n will be in the range [0, n] and sum will be in the range [0, sum].
- We initialize the 2D array with -1 to indicate that no subproblems have been computed yet.
- We check if the value at memo[n][sum] is -1. If it is, we proceed to compute the result. otherwise, we return the stored result.
C++
//C++ implementation for subset sum
// problem using memoization
#include <bits/stdc++.h>
using namespace std;
// Recursive function to check if a subset
// with the given sum exists
bool isSubsetSumRec(vector<int>& arr, int n, int sum,
vector<vector<int>> &memo) {
// If the sum is zero, we found a subset
if (sum == 0)
return 1;
// If no elements are left
if (n <= 0)
return 0;
// If the value is already
// computed, return it
if (memo[n][sum] != -1)
return memo[n][sum];
// If the last element is greater than
// the sum, ignore it
if (arr[n - 1] > sum)
return memo[n][sum] = isSubsetSumRec(arr, n - 1, sum, memo);
else {
// Include or exclude the last element
return memo[n][sum] = isSubsetSumRec(arr, n - 1, sum, memo) ||
isSubsetSumRec(arr, n - 1, sum - arr[n - 1], memo);
}
}
// Function to initiate the subset sum check
bool isSubsetSum(vector<int>&arr, int sum) {
int n = arr.size();
vector<vector<int>> memo(n + 1, vector<int>(sum + 1, -1));
return isSubsetSumRec(arr, n, sum, memo);
}
int main() {
vector<int>arr = {1, 5, 3, 7, 4};
int sum = 12;
if (isSubsetSum(arr, sum)) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
return 0;
}
Java
//Java implementation for subset sum
// problem using memoization
import java.util.Arrays;
class GfG {
// Recursive function to check if a subset
// with the given sum exists
static boolean isSubsetSumRec(int[] arr, int n, int sum,
int[][] memo) {
// If the sum is zero, we found a subset
if (sum == 0) {
return true;
}
// If no elements are left
if (n <= 0) {
return false;
}
// If the value is already computed, return it
if (memo[n][sum] != -1) {
return memo[n][sum] == 1;
}
// If the last element is greater than the sum,
// ignore it
if (arr[n - 1] > sum) {
memo[n][sum] = isSubsetSumRec(arr, n - 1, sum, memo)
? 1 : 0;
}
else {
// Include or exclude the last element directly
memo[n][sum] = (isSubsetSumRec(arr, n - 1, sum, memo)
|| isSubsetSumRec(arr, n - 1, sum - arr[n - 1], memo))
? 1 : 0;
}
return memo[n][sum] == 1;
}
// Function to initiate the subset sum check
static boolean isSubsetSum(int[] arr, int sum) {
int n = arr.length;
int[][] memo = new int[n + 1][sum + 1];
for (int[] row : memo) {
Arrays.fill(row, -1);
}
return isSubsetSumRec(arr, n, sum, memo);
}
public static void main(String[] args) {
int[] arr = { 1, 5, 3, 7, 4 };
int sum = 12;
if (isSubsetSum(arr, sum)) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
}
Python
# Python implementation for subset sum
# problem using memoization
def isSubsetSumRec(arr, n, sum, memo):
# If the sum is zero, we found
# a subset
if sum == 0:
return True
# If no elements are left
if n <= 0:
return False
# If the value is already
# computed, return it
if memo[n][sum] != -1:
return memo[n][sum]
# If the last element is greater
# than the sum, ignore it
if arr[n - 1] > sum:
memo[n][sum] = isSubsetSumRec(arr, n - 1, sum, memo)
else:
# Include or exclude the last element
# directly
memo[n][sum] = (isSubsetSumRec(arr, n - 1, sum, memo)
or isSubsetSumRec(arr, n - 1, sum - arr[n - 1], memo))
return memo[n][sum]
def isSubsetSum(arr, sum):
n = len(arr)
memo = [[-1 for _ in range(sum + 1)] for _ in range(n + 1)]
return isSubsetSumRec(arr, n, sum, memo)
if __name__ == "__main__":
arr = [1, 5, 3, 7, 4]
sum = 12
if isSubsetSum(arr, sum):
print("True")
else:
print("False")
C#
//C# implementation for subset sum
// problem using memoization
using System;
class GfG {
// Recursive function to check if a subset with
// the given sum exists
static bool isSubsetSumRec(int[] arr, int n, int sum,
int[, ] memo) {
// If the sum is zero, we found a subset
if (sum == 0)
return true;
// If no elements are left
if (n <= 0)
return false;
// If the value is already computed,
// return it
if (memo[n, sum] != -1)
return memo[n, sum] == 1;
// If the last element is greater
// than the sum, ignore it
if (arr[n - 1] > sum)
memo[n, sum]
= isSubsetSumRec(arr, n - 1, sum, memo) ? 1
: 0;
else {
// Include or exclude the last element directly
memo[n, sum]
= (isSubsetSumRec(arr, n - 1, sum, memo)
|| isSubsetSumRec(arr, n - 1, sum - arr[n - 1], memo))
? 1 : 0;
}
return memo[n, sum] == 1;
}
// Function to initiate the subset sum check
static bool isSubsetSum(int[] arr, int sum) {
int n = arr.Length;
int[, ] memo = new int[n + 1, sum + 1];
for (int i = 0; i <= n; i++)
for (int j = 0; j <= sum; j++)
memo[i, j] = -1;
return isSubsetSumRec(arr, n, sum, memo);
}
static void Main() {
int[] arr = { 1, 5, 3, 7, 4 };
int sum = 12;
if (isSubsetSum(arr, sum))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
//Javascript implementation for subset sum
// problem using memoization
function isSubsetSumRec(arr, n, sum, memo) {
// If the sum is zero, we found a subset
if (sum === 0) return true;
// If no elements are left
if (n <= 0) return false;
// If the value is already computed,
// return it
if (memo[n][sum] !== -1) return memo[n][sum] === 1;
// If the last element is greater than
// the sum, ignore it
if (arr[n - 1] > sum) {
memo[n][sum] = isSubsetSumRec(arr, n - 1, sum, memo) ? 1 : 0;
} else {
// Include or exclude the last element directly
memo[n][sum] = (isSubsetSumRec(arr, n - 1, sum, memo) ||
isSubsetSumRec(arr, n - 1, sum - arr[n - 1], memo))
? 1 : 0;
}
return memo[n][sum] === 1;
}
// Function to initiate the subset sum check
function isSubsetSum(arr, sum) {
const n = arr.length;
const memo = Array.from(Array(n + 1), () => Array(sum + 1).fill(-1));
return isSubsetSumRec(arr, n, sum, memo);
}
const arr = [1, 5, 3, 7, 4];
const sum = 12;
if (isSubsetSum(arr, sum)) {
console.log("True");
} else {
console.log("False");
}
[Better Approach 2] Using Bottom-Up DP (Tabulation) - O(sum*n) Time and O(sum*n) Space
The approach is similar to the previous one. just instead of breaking down the problem recursively, we iteratively build up the solution by calculating in bottom-up manner.
So we will create a 2D array of size (n + 1) * (sum + 1) of type boolean. The state dp[i][j] will be true if there exists a subset of elements from arr[0 . . . i] with sum = 'j'.
The dynamic programming relation is as follows:
if (arr[i-1] > j)
dp[i][j] = dp[i-1][j]
else
dp[i][j] = dp[i-1][j] OR dp[i-1][j-arr[i-1]]
This means that if the current element has a value greater than the 'current sum value' we will copy the answer for previous cases and if the current sum value is greater than the 'ith' element we will see if any of the previous states have already computed the sum= j OR any previous states computed a value 'j - arr[i]' which will solve our purpose.
C++
//C++ implementation for subset sum
// problem using tabulation
#include <bits/stdc++.h>
using namespace std;
// Function to check if there is a subset of arr[]
// with sum equal to the given sum using tabulation with vectors
bool isSubsetSum(vector<int> &arr, int sum) {
int n = arr.size();
// Create a 2D vector for storing results
// of subproblems
vector<vector<bool>> dp(n + 1, vector<bool>(sum + 1, false));
// If sum is 0, then answer is true (empty subset)
for (int i = 0; i <= n; i++)
dp[i][0] = true;
// Fill the dp table in bottom-up manner
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
if (j < arr[i - 1]) {
// Exclude the current element
dp[i][j] = dp[i - 1][j];
}
else {
// Include or exclude
dp[i][j] = dp[i - 1][j]
|| dp[i - 1][j - arr[i - 1]];
}
}
}
return dp[n][sum];
}
int main() {
vector<int> arr = {3, 34, 4, 12, 5, 2};
int sum = 9;
if (isSubsetSum(arr, sum))
cout << "True" << endl;
else
cout << "False" << endl;
return 0;
}
Java
//Java implementation for subset sum
// problem using tabulation
import java.util.*;
class GfG {
// Function to check if there is a subset of arr[]
// with sum equal to the given sum using tabulation
static boolean isSubsetSum(int[] arr, int sum) {
int n = arr.length;
// Create a 2D array for storing results of
// subproblems
boolean[][] dp = new boolean[n + 1][sum + 1];
// If sum is 0, then answer is true
// (empty subset)
for (int i = 0; i <= n; i++) {
dp[i][0] = true;
}
// Fill the dp table in bottom-up manner
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
if (j < arr[i - 1]) {
// Exclude the current element
dp[i][j] = dp[i - 1][j];
}
else {
// Include or exclude
dp[i][j] = dp[i - 1][j]
|| dp[i - 1][j - arr[i - 1]];
}
}
}
return dp[n][sum];
}
public static void main(String[] args) {
int[] arr = { 3, 34, 4, 12, 5, 2 };
int sum = 9;
if (isSubsetSum(arr, sum)) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
}
Python
# Python implementation for subset sum
# problem using tabulation
def isSubsetSum(arr, sum):
n = len(arr)
# Create a 2D list for storing
# results of subproblems
dp = [[False] * (sum + 1) for _ in range(n + 1)]
# If sum is 0, then answer is
# true (empty subset)
for i in range(n + 1):
dp[i][0] = True
# Fill the dp table in bottom-up manner
for i in range(1, n + 1):
for j in range(1, sum + 1):
if j < arr[i - 1]:
# Exclude the current element
dp[i][j] = dp[i - 1][j]
else:
# Include or exclude
dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]
return dp[n][sum]
if __name__ == "__main__":
arr = [3, 34, 4, 12, 5, 2]
sum_value = 9
if isSubsetSum(arr, sum_value):
print("True")
else:
print("False")
C#
//C# implementation for subset sum
// problem using tabulation
using System;
class GfG {
// Function to check if there is a subset of arr[]
// with sum equal to the given sum using tabulation
static bool isSubsetSum(int[] arr, int sum) {
int n = arr.Length;
// Create a 2D array for storing results of
// subproblems
bool[, ] dp = new bool[n + 1, sum + 1];
// If sum is 0, then answer is true
// (empty subset)
for (int i = 0; i <= n; i++)
dp[i, 0] = true;
// Fill the dp table in bottom-up manner
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
if (j < arr[i - 1]) {
// Exclude the current element
dp[i, j] = dp[i - 1, j];
}
else {
// Include or exclude
dp[i, j] = dp[i - 1, j]
|| dp[i - 1, j - arr[i - 1]];
}
}
}
return dp[n, sum];
}
static void Main(string[] args) {
int[] arr = { 3, 34, 4, 12, 5, 2 };
int sum = 9;
if (isSubsetSum(arr, sum))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
//Javascript implementation for subset sum
// problem using tabulation
function isSubsetSum(arr, sum) {
const n = arr.length;
// Create a 2D array for storing results
// of subproblems
const dp = Array.from(Array(n + 1), () => Array(sum + 1).fill(false));
// If sum is 0, then answer is
// true (empty subset)
for (let i = 0; i <= n; i++) {
dp[i][0] = true;
}
// Fill the dp table in bottom-up manner
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= sum; j++) {
if (j < arr[i - 1]) {
// Exclude the current element
dp[i][j] = dp[i - 1][j];
} else {
// Include or exclude
dp[i][j] = dp[i - 1][j]
|| dp[i - 1][j - arr[i - 1]];
}
}
}
return dp[n][sum];
}
// Driver code
const arr = [3, 34, 4, 12, 5, 2];
const sum = 9;
if (isSubsetSum(arr, sum)) {
console.log("True");
} else {
console.log("False");
}
[Expected Approach] Using Space Optimized DP – O(sum*n) Time and O(sum) Space
In previous approach of dynamic programming we have derive the relation between states as given below:
if (arr[i-1] > j)
dp[i][j] = dp[i-1][j]
else
dp[i][j] = dp[i-1][j] OR dp[i-1][j-arr[i-1]]
If we observe that for calculating current dp[i][j] state we only need previous row dp[i-1][j] or dp[i-1][j-arr[i-1]]. There is no need to store all the previous states just one previous state is used to compute result.
Approach:
- Define two arrays prev and curr of size sum+1 to store the just previous row result and current row result respectively.
- Once curr array is calculated then curr becomes our prev for the next row.
- When all rows are processed the answer is stored in prev array.
C++
// C++ Program for Space Optimized Dynamic Programming
// Solution to Subset Sum Problem
#include <bits/stdc++.h>
using namespace std;
// Returns true if there is a subset of arr[]
// with sum equal to given sum
bool isSubsetSum(vector<int> arr, int sum) {
int n = arr.size();
vector<bool> prev(sum + 1, false), curr(sum + 1);
// Mark prev[0] = true as it is true
// to make sum = 0 using 0 elements
prev[0] = true;
// Fill the subset table in
// bottom up manner
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= sum; j++) {
if (j < arr[i - 1])
curr[j] = prev[j];
else
curr[j] = (prev[j] || prev[j - arr[i - 1]]);
}
prev = curr;
}
return prev[sum];
}
int main() {
vector<int> arr = {3, 34, 4, 12, 5, 2};
int sum = 9;
if (isSubsetSum(arr, sum) == true)
cout << "True";
else
cout << "False";
return 0;
}
Java
// Java Program for Space Optimized Dynamic Programming
// Solution to Subset Sum Problem
import java.util.Arrays;
class GfG {
// Returns true if there is a subset of arr[]
// with sum equal to given sum
static boolean isSubsetSum(int[] arr, int sum) {
int n = arr.length;
boolean[] prev = new boolean[sum + 1];
boolean[] curr = new boolean[sum + 1];
// Mark prev[0] = true as it is true to
// make sum = 0 using 0 elements
prev[0] = true;
// Fill the subset table in bottom-up
// manner
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= sum; j++) {
if (j < arr[i - 1]) {
curr[j] = prev[j];
}
else {
curr[j]
= prev[j] || prev[j - arr[i - 1]];
}
}
// Update prev to be the current row
System.arraycopy(curr, 0, prev, 0, sum + 1);
}
return prev[sum];
}
public static void main(String[] args) {
int[] arr = { 3, 34, 4, 12, 5, 2 };
int sum = 9;
if (isSubsetSum(arr, sum)) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
}
Python
# Python Program for Space Optimized Dynamic Programming
# Solution to Subset Sum Problem
def isSubsetSum(arr, sum):
n = len(arr)
prev = [False] * (sum + 1)
curr = [False] * (sum + 1)
# Base case: sum 0 can always
# be achieved
prev[0] = True
# Fill the dp table in a
# bottom-up manner
for i in range(1, n + 1):
for j in range(sum + 1):
if j < arr[i - 1]:
curr[j] = prev[j]
else:
curr[j] = prev[j] or prev[j - arr[i - 1]]
prev = curr.copy()
return prev[sum]
if __name__ == "__main__":
arr = [3, 34, 4, 12, 5, 2]
sum_value = 9
if isSubsetSum(arr, sum_value):
print("True")
else:
print("False")
C#
// C# Program for Space Optimized Dynamic Programming
// Solution to Subset Sum Problem
using System;
class GfG {
static bool isSubsetSum(int[] arr, int sum) {
int n = arr.Length;
bool[] prev = new bool[sum + 1];
bool[] curr = new bool[sum + 1];
// Base case: sum 0 can
// always be achieved
prev[0] = true;
// Fill the dp table in a
// bottom-up manner
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= sum; j++) {
if (j < arr[i - 1])
curr[j] = prev[j];
else
curr[j]
= prev[j] || prev[j - arr[i - 1]];
}
Array.Copy(curr, prev,
sum + 1);
}
return prev[sum];
}
static void Main() {
int[] arr = { 3, 34, 4, 12, 5, 2 };
int sum = 9;
if (isSubsetSum(arr, sum))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
// Javascript Program for Space Optimized Dynamic Programming
// Solution to Subset Sum Problem
function isSubsetSum(arr, sum) {
const n = arr.length;
const prev = new Array(sum + 1).fill(false);
const curr = new Array(sum + 1).fill(false);
// Base case: sum 0 can always
// be achieved
prev[0] = true;
// Fill the dp table in a
// bottom-up manner
for (let i = 1; i <= n; i++) {
for (let j = 0; j <= sum; j++) {
if (j < arr[i - 1]) {
curr[j] = prev[j];
} else {
curr[j] = prev[j] || prev[j - arr[i - 1]];
}
}
// Update prev to be the current row
for (let j = 0; j <= sum; j++) {
prev[j] = curr[j];
}
}
return prev[sum];
}
// Driver code
const arr = [3, 34, 4, 12, 5, 2];
const sum = 9;
if (isSubsetSum(arr, sum)) {
console.log("True");
} else {
console.log("False");
}
Related articles:
Dynamic Programming - Subset Sum Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem