Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Python Program for Subset Sum Problem | DP-25
Next article icon

Subset Sum Problem

Last Updated : 15 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.

Table of Content

  • [Naive Approach] Using Recursion – O(2^n) Time and O(n) Space
  • [Better Approach 1] Using Top-Down DP (Memoization) – O(sum*n) Time and O(sum*n) Space
  • [Better Approach 2] Using Bottom-Up DP (Tabulation) – O(sum*n) Time and O(sum*n) Space
  • [Expected Approach] Using Space Optimized DP – O(sum*n) Time and O(sum) Space

[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"); } 

Output
True 

[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.

subset-sum-problem

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"); } 

Output
True 

[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"); } 

Output
True 

[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"); } 

Output
True

Related articles:

  • Subset Sum Problem in O(sum) space 
  • Perfect Sum Problem (Print all subsets with given sum)


Next Article
Python Program for Subset Sum Problem | DP-25
author
kartik
Improve
Article Tags :
  • Arrays
  • DSA
  • Dynamic Programming
  • Adobe
  • Adobe-Question
  • Amazon
  • Drishti-Soft
  • subset
Practice Tags :
  • Adobe
  • Amazon
  • Drishti-Soft
  • Arrays
  • Dynamic Programming
  • subset

Similar Reads

  • Subset Sum Problem
    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 = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: arr[] = [3, 34,
    15+ min read
  • Subset sum in Different languages

    • Python Program for Subset Sum Problem | DP-25
      Write a Python program for a given set of non-negative integers and a value sum, the task is to check if there is a subset of the given set whose sum is equal to the given sum. Examples: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input:
      7 min read

    • Java Program for Subset Sum Problem | DP-25
      Write a Java program for a given set of non-negative integers and a value sum, the task is to check if there is a subset of the given set whose sum is equal to the given sum. Examples: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: se
      8 min read

    • C Program for Subset Sum Problem | DP-25
      Write a C program for a given set of non-negative integers and a value sum, the task is to check if there is a subset of the given set whose sum is equal to the given sum. Examples: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: set[]
      8 min read

    • PHP Program for Subset Sum Problem | DP-25
      Write a PHP program for a given set of non-negative integers and a value sum, the task is to check if there is a subset of the given set whose sum is equal to the given sum. Examples: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: set
      7 min read

    • C# Program for Subset Sum Problem | DP-25
      Write a C# program for a given set of non-negative integers and a value sum, the task is to check if there is a subset of the given set whose sum is equal to the given sum. Examples: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: set[
      8 min read

  • Subset Sum Problem using Backtracking
    Given a set[] of non-negative integers and a value sum, the task is to print the subset of the given set whose sum is equal to the given sum. Examples:  Input: set[] = {1,2,1}, sum = 3Output: [1,2],[2,1]Explanation: There are subsets [1,2],[2,1] with sum 3. Input: set[] = {3, 34, 4, 12, 5, 2}, sum =
    8 min read
  • Print all subsets with given sum
    Given an array arr[] of non-negative integers and an integer target. The task is to print all subsets of the array whose sum is equal to the given target. Note: If no subset has a sum equal to target, print -1. Examples: Input: arr[] = [5, 2, 3, 10, 6, 8], target = 10Output: [ [5, 2, 3], [2, 8], [10
    15+ min read
  • Subset Sum Problem in O(sum) space
    Given an array of non-negative integers and a value sum, determine if there is a subset of the given set with sum equal to given sum. Examples: Input: arr[] = {4, 1, 10, 12, 5, 2}, sum = 9Output: TRUEExplanation: {4, 5} is a subset with sum 9. Input: arr[] = {1, 8, 2, 5}, sum = 4Output: FALSE Explan
    13 min read
  • Subset Sum is NP Complete
    Prerequisite: NP-Completeness, Subset Sum Problem Subset Sum Problem: Given N non-negative integers a1...aN and a target sum K, the task is to decide if there is a subset having a sum equal to K. Explanation: An instance of the problem is an input specified to the problem. An instance of the subset
    5 min read
  • Minimum Subset sum difference problem with Subset partitioning
    Given a set of N integers with up to 40 elements, the task is to partition the set into two subsets of equal size (or the closest possible), such that the difference between the sums of the subsets is minimized. If the size of the set is odd, one subset will have one more element than the other. If
    13 min read
  • Maximum subset sum such that no two elements in set have same digit in them
    Given an array of N elements. Find the subset of elements which has maximum sum such that no two elements in the subset has common digit present in them.Examples: Input : array[] = {22, 132, 4, 45, 12, 223} Output : 268 Maximum Sum Subset will be = {45, 223} . All possible digits are present except
    12 min read
  • Find all distinct subset (or subsequence) sums of an array
    Given an array arr[] of size n, the task is to find a distinct sum that can be generated from the subsets of the given sets and return them in increasing order. It is given that the sum of array elements is small. Examples: Input: arr[] = [1, 2]Output: [0, 1, 2, 3]Explanation: Four distinct sums can
    15+ min read
  • Subset sum problem where Array sum is at most N
    Given an array arr[] of size N such that the sum of all the array elements does not exceed N, and array queries[] containing Q queries. For each query, the task is to find if there is a subset of the array whose sum is the same as queries[i]. Examples: Input: arr[] = {1, 0, 0, 0, 0, 2, 3}, queries[]
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences