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 = 9
Output : TRUE
{4, 5} is a subset with sum 9.
Input : arr[] = {1, 8, 2, 5}, 
          sum = 4
Output : FALSE 
There exists no subset with sum 4.
We have discussed a Dynamic Programming based solution in below post. 
Dynamic Programming | Set 25 (Subset Sum Problem)
The solution discussed above requires O(n * sum) space and O(n * sum) time. We can optimize space. We create a boolean 2D array subset[2][sum+1]. Using bottom-up manner we can fill up this table. The idea behind using 2 in “subset[2][sum+1]” is that for filling a row only the values from previous row are required. So alternate rows are used either making the first one as current and second as previous or the first as previous and second as current. 
C++
| // Returns true if there exists a subset // with given sum in arr[] #include <iostream> usingnamespacestd;  boolisSubsetSum(intarr[], intn, intsum) {        // The value of subset[i%2][j] will be true      // if there exists a subset of sum j in      // arr[0, 1, ...., i-1]     boolsubset[2][sum + 1];      for(inti = 0; i <= n; i++) {         for(intj = 0; j <= sum; j++) {              // A subset with sum 0 is always possible              if(j == 0)                 subset[i % 2][j] = true;               // If there exists no element no sum              // is possible              elseif(i == 0)                 subset[i % 2][j] = false;              elseif(arr[i - 1] <= j)                 subset[i % 2][j] = subset[(i + 1) % 2]              [j - arr[i - 1]] || subset[(i + 1) % 2][j];             else                subset[i % 2][j] = subset[(i + 1) % 2][j];         }     }      returnsubset[n % 2][sum]; }  // Driver code intmain() {     intarr[] = { 6, 2, 5 };     intsum = 7;     intn = sizeof(arr) / sizeof(arr[0]);     if(isSubsetSum(arr, n, sum) == true)         cout <<"There exists a subset with given sum";     else        cout <<"No subset exists with given sum";     return0; }  // This code is contributed by shivanisinghss2110 | 
C
| // Returns true if there exists a subset // with given sum in arr[] #include <stdio.h> #include <stdbool.h>  boolisSubsetSum(intarr[], intn, intsum) {     // The value of subset[i%2][j] will be true      // if there exists a subset of sum j in      // arr[0, 1, ...., i-1]     boolsubset[2][sum + 1];      for(inti = 0; i <= n; i++) {         for(intj = 0; j <= sum; j++) {              // A subset with sum 0 is always possible              if(j == 0)                 subset[i % 2][j] = true;               // If there exists no element no sum              // is possible              elseif(i == 0)                 subset[i % 2][j] = false;              elseif(arr[i - 1] <= j)                 subset[i % 2][j] = subset[(i + 1) % 2]              [j - arr[i - 1]] || subset[(i + 1) % 2][j];             else                subset[i % 2][j] = subset[(i + 1) % 2][j];         }     }      returnsubset[n % 2][sum]; }  // Driver code intmain() {     intarr[] = { 6, 2, 5 };     intsum = 7;     intn = sizeof(arr) / sizeof(arr[0]);     if(isSubsetSum(arr, n, sum) == true)         printf("There exists a subset with given sum");     else        printf("No subset exists with given sum");     return0; }  | 
Java
| // Java Program to get a subset with a  // with a sum provided by the user publicclassSubset_sum {          // Returns true if there exists a subset     // with given sum in arr[]     staticbooleanisSubsetSum(intarr[], intn, intsum)     {         // The value of subset[i%2][j] will be true          // if there exists a subset of sum j in          // arr[0, 1, ...., i-1]         booleansubset[][] = newboolean[2][sum + 1];               for(inti = 0; i <= n; i++) {             for(intj = 0; j <= sum; j++) {                       // A subset with sum 0 is always possible                  if(j == 0)                     subset[i % 2][j] = true;                        // If there exists no element no sum                  // is possible                  elseif(i == 0)                     subset[i % 2][j] = false;                  elseif(arr[i - 1] <= j)                     subset[i % 2][j] = subset[(i + 1) % 2]                  [j - arr[i - 1]] || subset[(i + 1) % 2][j];                 else                    subset[i % 2][j] = subset[(i + 1) % 2][j];             }         }               returnsubset[n % 2][sum];     }           // Driver code     publicstaticvoidmain(String args[])     {         intarr[] = { 1, 2, 5};         intsum = 7;         intn = arr.length;         if(isSubsetSum(arr, n, sum) == true)             System.out.println("There exists a subset with"+                                                " given sum");         else            System.out.println("No subset exists with"+                                             " given sum");     } } // This code is contributed by Sumit Ghosh  | 
Python
| # Returns true if there exists a subset # with given sum in arr[]   defisSubsetSum(arr, n, sum):      # The value of subset[i%2][j] will be true     # if there exists a subset of sum j in     # arr[0, 1, ...., i-1]     subset =[[Falseforj inrange(sum+1)] fori inrange(3)]      fori inrange(n +1):         forj inrange(sum+1):             # A subset with sum 0 is always possible             if(j ==0):                 subset[i %2][j] =True             # If there exists no element no sum             # is possible             elif(i ==0):                 subset[i %2][j] =False            elif(arr[i -1] <=j):                 subset[i %2][j] =subset[(i +1) %2][j -arr[i -1]] orsubset[(i +1)                                                                                  %2][j]             else:                 subset[i %2][j] =subset[(i +1) %2][j]      returnsubset[n %2][sum]   # Driver code arr =[6, 2, 5] sum=7n =len(arr) if(isSubsetSum(arr, n, sum) ==True):     print("There exists a subset with given sum") else:     print("No subset exists with given sum")  # This code is contributed by Sachin Bisht  | 
C#
| // C# Program to get a subset with a  // with a sum provided by the user   usingSystem;  publicclassSubset_sum {           // Returns true if there exists a subset      // with given sum in arr[]      staticboolisSubsetSum(int[]arr, intn, intsum)      {          // The value of subset[i%2][j] will be true          // if there exists a subset of sum j in          // arr[0, 1, ...., i-1]          bool[,]subset = newbool[2,sum + 1];               for(inti = 0; i <= n; i++) {              for(intj = 0; j <= sum; j++) {                       // A subset with sum 0 is always possible                  if(j == 0)                      subset[i % 2,j] = true;                       // If there exists no element no sum                  // is possible                  elseif(i == 0)                      subset[i % 2,j] = false;                  elseif(arr[i - 1] <= j)                      subset[i % 2,j] = subset[(i + 1) % 2,j - arr[i - 1]] || subset[(i + 1) % 2,j];                  else                    subset[i % 2,j] = subset[(i + 1) % 2,j];              }          }               returnsubset[n % 2,sum];      }           // Driver code      publicstaticvoidMain()      {          int[]arr = { 1, 2, 5 };          intsum = 7;          intn = arr.Length;          if(isSubsetSum(arr, n, sum) == true)              Console.WriteLine("There exists a subset with"+                                          "given sum");          else            Console.WriteLine("No subset exists with"+                                          "given sum");      }  }  // This code is contributed by Ryuga   | 
PHP
| <?php // Returns true if there exists a subset // with given sum in arr[]  functionisSubsetSum($arr, $n, $sum) {     // The value of subset[i%2][j] will be      // true if there exists a subset of      // sum j in arr[0, 1, ...., i-1]     $subset[2][$sum+ 1] = array();      for($i= 0; $i<= $n; $i++)      {         for($j= 0; $j<= $sum; $j++)         {              // A subset with sum 0 is              // always possible              if($j== 0)                 $subset[$i% 2][$j] = true;               // If there exists no element no              // sum is possible              elseif($i== 0)                 $subset[$i% 2][$j] = false;              elseif($arr[$i- 1] <= $j)                 $subset[$i% 2][$j] = $subset[($i+ 1) % 2]                                              [$j- $arr[$i- 1]] ||                                        $subset[($i+ 1) % 2][$j];             else                $subset[$i% 2][$j] = $subset[($i+ 1) % 2][$j];         }     }      return$subset[$n% 2][$sum]; }  // Driver code $arr= array( 6, 2, 5 ); $sum= 7; $n= sizeof($arr); if(isSubsetSum($arr, $n, $sum) == true)     echo("There exists a subset with given sum"); else    echo("No subset exists with given sum");  // This code is contributed by Sach_Code ?>  | 
Javascript
| <script>  // Javascript Program to get a subset with a  // with a sum provided by the user      // Returns true if there exists a subset     // with given sum in arr[]     functionisSubsetSum(arr, n, sum)     {         // The value of subset[i%2][j] will be true          // if there exists a subset of sum j in          // arr[0, 1, ...., i-1]         let subset = newArray(2);                  // Loop to create 2D array using 1D array         for(vari = 0; i < subset.length; i++) {             subset[i] = newArray(2);         }                 for(let i = 0; i <= n; i++) {             for(let j = 0; j <= sum; j++) {                         // A subset with sum 0 is always possible                  if(j == 0)                     subset[i % 2][j] = true;                          // If there exists no element no sum                  // is possible                  elseif(i == 0)                     subset[i % 2][j] = false;                  elseif(arr[i - 1] <= j)                     subset[i % 2][j] = subset[(i + 1) % 2]                  [j - arr[i - 1]] || subset[(i + 1) % 2][j];                 else                    subset[i % 2][j] = subset[(i + 1) % 2][j];             }         }                 returnsubset[n % 2][sum];     }  // driver program         let arr = [ 1, 2, 5 ];         let sum = 7;         let n = arr.length;         if(isSubsetSum(arr, n, sum) == true)             document.write("There exists a subset with"+                                                "given sum");         else            document.write("No subset exists with"+                                             "given sum");  // This code is contributed by code_hunt. </script>  | 
There exists a subset with given sum
Another Approach: To further reduce space complexity, we create a boolean 1D array subset[sum+1]. Using bottom-up manner we can fill up this table. The idea is that we can check if the sum till position “i” is possible then if the current element in the array at position j is x, then sum i+x is also possible. We traverse the sum array from back to front so that we don’t count any element twice.
Here’s the code for the given approach:
C++
| #include <iostream> usingnamespacestd;  boolisPossible(intelements[], intsum, intn) {     intdp[sum + 1];          // Initializing with 1 as sum 0 is      // always possible     dp[0] = 1;          // Loop to go through every element of     // the elements array     for(inti = 0; i < n; i++)     {                  // To change the values of all possible sum         // values to 1         for(intj = sum; j >= elements[i]; j--)          {             if(dp[j - elements[i]] == 1)                 dp[j] = 1;         }     }          // If sum is possible then return 1     if(dp[sum] == 1)         returntrue;              returnfalse; }  // Driver code intmain() {     intelements[] = { 6, 2, 5 };     intn = sizeof(elements) / sizeof(elements[0]);     intsum = 7;          if(isPossible(elements, sum, n))         cout << ("YES");     else        cout << ("NO");      return0; }  // This code is contributed by Potta Lokesh | 
Java
| importjava.io.*; importjava.util.*; classGFG {     staticbooleanisPossible(intelements[], intsum)     {         intdp[] = newint[sum + 1];         // initializing with 1 as sum 0 is always possible         dp[0] = 1;         // loop to go through every element of the elements         // array         for(inti = 0; i < elements.length; i++) {             // to change the values of all possible sum             // values to 1             for(intj = sum; j >= elements[i]; j--) {                 if(dp[j - elements[i]] == 1)                     dp[j] = 1;             }         }         // if sum is possible then return 1         if(dp[sum] == 1)             returntrue;         returnfalse;     }     publicstaticvoidmain(String[] args) throwsException     {         intelements[] = { 6, 2, 5};         intsum = 7;         if(isPossible(elements, sum))             System.out.println("YES");         else            System.out.println("NO");     } } | 
Python3
| defisPossible(elements, target):      dp =[False]*(target+1)      # initializing with 1 as sum 0 is always possible     dp[0] =True     # loop to go through every element of the elements array     forele inelements:                # to change the value o all possible sum values to True         forj inrange(target, ele -1, -1):             ifdp[j -ele]:                 dp[j] =True     # If target is possible return True else False     returndp[target]  # Driver code arr =[6, 2, 5] target =7 ifisPossible(arr, target):     print("YES") else:     print("NO")  # The code is contributed by Arpan.  | 
C#
| usingSystem;  classGFG {     staticBoolean isPossible(int[]elements, intsum)     {         int[]dp = newint[sum + 1];                // initializing with 1 as sum 0 is always possible         dp[0] = 1;                // loop to go through every element of the elements         // array         for(inti = 0; i < elements.Length; i++)          {                        // to change the values of all possible sum             // values to 1             for(intj = sum; j >= elements[i]; j--) {                 if(dp[j - elements[i]] == 1)                     dp[j] = 1;             }         }                // if sum is possible then return 1         if(dp[sum] == 1)             returntrue;         returnfalse;     }      // Driver code     publicstaticvoidMain(String[] args)     {         int[]elements = { 6, 2, 5 };         intsum = 7;         if(isPossible(elements, sum))             Console.Write("YES");         else            Console.Write("NO");     } }  // This code is contributed by shivanisinghss2110 | 
Javascript
| <script> functionisPossible(elements, sum)     {         vardp =  [sum + 1];                  // initializing with 1 as sum 0 is always possible         dp[0] = 1;                  // loop to go through every element of the elements         // array         for(vari = 0; i < elements.length; i++)         {                      // to change the values of all possible sum             // values to 1             for(varj = sum; j >= elements[i]; j--) {                 if(dp[j - elements[i]] == 1)                     dp[j] = 1;             }         }                  // if sum is possible then return 1         if(dp[sum] == 1)             returntrue;         returnfalse;     }         varelements = [ 6, 2, 5 ];         varsum = 7;         if(isPossible(elements, sum))             document.write("YES");         else            document.write("NO");              // This code is contributed by shivanisinghss2110 </script>  | 
YES
Time Complexity: O(N*K) where N is the number of elements in the array and K is total sum.
Auxiliary Space: O(K), since K extra space has been taken.
This article is contributed by Neelesh (Neelesh_Sinha). If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







