The Wayback Machine - https://web.archive.org/web/20240606140951/https://www.geeksforgeeks.org/subset-sum-problem-osum-space/
Open In App

Subset Sum Problem in O(sum) space

Last Updated : 16 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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
Explanation: {4, 5} is a subset with sum 9.

Input: arr[] = {1, 8, 2, 5}, sum = 4
Output: FALSE
Explanation: There exists no subset with sum 4.

We have discussed a Dynamic Programming based solution in the post “Dynamic Programming | Set 25 (Subset Sum Problem)“.

Subset Sum Problem in O(sum) space using 2D array:

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. 

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

bool isSubsetSum(int arr[], int n, int sum)
{
    // The value of subset[i][j] will be true 
    // if there exists a subset of sum j in 
    // arr[0, 1, ...., i-1]
    bool subset[n+1][sum + 1];

    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= sum; j++) {

            // A subset with sum 0 is always possible 
            if (j == 0)
                subset[i][j] = true; 

            // If there exists no element no sum 
            // is possible 
            else if (i == 0)
                subset[i][j] = false; 
            else if (arr[i - 1] <= j)
                subset[i][j] = subset[i - 1][j - arr[i - 1]] || subset[i - 1][j];
            else
                subset[i][j] = subset[i - 1][j];
        }
    }

    return subset[n][sum];
}

// Driver code
int main()
{
    int arr[] = { 6, 2, 5 };
    int sum = 7;
    int n = 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";
    return 0;
}
C
// Returns true if there exists a subset
// with given sum in arr[]
#include <stdio.h>
#include <stdbool.h>

bool isSubsetSum(int arr[], int n, int 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]
    bool subset[2][sum + 1];

    for (int i = 0; i <= n; i++) {
        for (int 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 
            else if (i == 0)
                subset[i % 2][j] = false; 
            else if (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
int main()
{
    int arr[] = { 6, 2, 5 };
    int sum = 7;
    int n = 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");
    return 0;
}
Java
// Java Program to get a subset with a 
// with a sum provided by the user
public class Subset_sum {
    
    // Returns true if there exists a subset
    // with given sum in arr[]
    static boolean isSubsetSum(int arr[], int n, int 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]
        boolean subset[][] = new boolean[2][sum + 1];
     
        for (int i = 0; i <= n; i++) {
            for (int 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 
                else if (i == 0)
                    subset[i % 2][j] = false; 
                else if (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
    public static void main(String args[])
    {
        int arr[] = { 1, 2, 5 };
        int sum = 7;
        int n = 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[]


def isSubsetSum(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 = [[False for j in range(sum + 1)] for i in range(3)]

    for i in range(n + 1):
        for j in range(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]] or subset[(i + 1)
                                                                                 % 2][j]
            else:
                subset[i % 2][j] = subset[(i + 1) % 2][j]

    return subset[n % 2][sum]


# Driver code
arr = [6, 2, 5]
sum = 7
n = 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 

using System;

public class Subset_sum { 
    
    // Returns true if there exists a subset 
    // with given sum in arr[] 
    static bool isSubsetSum(int []arr, int n, int 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] 
        bool [,]subset = new bool[2,sum + 1]; 
    
        for (int i = 0; i <= n; i++) { 
            for (int 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 
                else if (i == 0) 
                    subset[i % 2,j] = false; 
                else if (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 
    public static void Main() 
    { 
        int []arr = { 1, 2, 5 }; 
        int sum = 7; 
        int n = 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 
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[]
    function isSubsetSum(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 = new Array(2);
        
        // Loop to create 2D array using 1D array
        for (var i = 0; i < subset.length; i++) {
            subset[i] = new Array(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 
                else if (i == 0)
                    subset[i % 2][j] = false; 
                else if (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 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>
PHP
<?php
// Returns true if there exists a subset
// with given sum in arr[]

function isSubsetSum($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 
            else if ($i == 0)
                $subset[$i % 2][$j] = false; 
            else if ($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
?>

Output
There exists a subset with given sum

Subset Sum Problem in O(sum) space using 1D array:

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. 

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

bool isPossible(int elements[], int sum, int n)
{
    int dp[sum + 1] = { 0 };

    // Initializing with 1 as sum 0 is
    // always possible
    dp[0] = 1;

    // Loop to go through every element of
    // the elements array
    for (int i = 0; i < n; i++) {

        // To change the values of all possible sum
        // values to 1
        for (int j = 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)
        return true;

    return false;
}

// Driver code
int main()
{
    int elements[] = { 6, 2, 5 };
    int n = sizeof(elements) / sizeof(elements[0]);
    int sum = 7;

    if (isPossible(elements, sum, n))
        cout << ("YES");
    else
        cout << ("NO");

    return 0;
}

// This code is contributed by Potta Lokesh
// This code is modified by Susobhan Akhuli
Java
import java.io.*;
import java.util.*;

class GFG {
    static boolean isPossible(int elements[], int sum)
    {
        int dp[] = new int[sum + 1];
        Arrays.fill(dp, 0);

        // initializing with 1 as sum 0 is always possible
        dp[0] = 1;

        // loop to go through every element of the elements
        // array
        for (int i = 0; i < elements.length; i++) {
            // to change the values of all possible sum
            // values to 1
            for (int j = 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)
            return true;
        return false;
    }

    public static void main(String[] args) throws Exception
    {
        int elements[] = { 6, 2, 5 };
        int sum = 7;
        if (isPossible(elements, sum))
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}

// This code is modified by Susobhan Akhuli
Python
def isPossible(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
    for ele in elements:
      
        # to change the value o all possible sum values to True
        for j in range(target, ele - 1, -1):
            if dp[j - ele]:
                dp[j] = True

    # If target is possible return True else False
    return dp[target]

# Driver code
arr = [6, 2, 5]
target = 7

if isPossible(arr, target):
    print("YES")
else:
    print("NO")

# The code is contributed by Arpan.
C#
using System;

class GFG {
    static Boolean isPossible(int[] elements, int sum)
    {
        int[] dp = new int[sum + 1];
        Array.Fill(dp, 0);

        // initializing with 1 as sum 0 is always possible
        dp[0] = 1;

        // loop to go through every element of the elements
        // array
        for (int i = 0; i < elements.Length; i++) {

            // to change the values of all possible sum
            // values to 1
            for (int j = 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)
            return true;
        return false;
    }

    // Driver code
    public static void Main(String[] args)
    {
        int[] elements = { 6, 2, 5 };
        int sum = 7;
        if (isPossible(elements, sum))
            Console.Write("YES");
        else
            Console.Write("NO");
    }
}

// This code is contributed by shivanisinghss2110
// This code is modified by Susobhan Akhuli
Javascript
<script>
function isPossible(elements, sum)
    {
        var dp = Array(sum+1).fill(0);
        
        // initializing with 1 as sum 0 is always possible
        dp[0] = 1;
        
        // loop to go through every element of the elements
        // array
        for (var i = 0; i < elements.length; i++)
        {
        
            // to change the values of all possible sum
            // values to 1
            for (var j = 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)
            return true;
        return false;
    }
        var elements = [ 6, 2, 5 ];
        var sum = 7;
        if (isPossible(elements, sum))
            document.write("YES");
        else
            document.write("NO");
            
// This code is contributed by shivanisinghss2110
// This code is modified by Susobhan Akhuli
</script>

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



Previous Article
Next Article

Similar Reads

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 the size is even, both subsets will have the same
13 min read
Sum of maximum and minimum of Kth subset ordered by increasing subset sum
Given an integer N and a set of all non-negative powers of N as S = {N0, N1, N2, N3, ... }, arrange all non-empty subsets of S in increasing order of subset-sum. The task is to find the sum of the greatest and smallest elements of the Kth subset from that ordering. Examples: Input: N = 4, K = 3Output: 5Explanation: S = {1, 4, 16, 64, ...}.Therefore
7 min read
Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum
Given an array A containing N elements. Partition any subset of this array into two disjoint subsets such that both the subsets have an identical sum. Obtain the maximum sum that can be obtained after partitioning. Note: It is not necessary to partition the entire array, that is any element might not contribute to any of the partition. Examples: In
24 min read
Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N
Given an array of N integers, the task is to find a non-empty subset such that the sum of elements of the subset is divisible by N. Output any such subset with its size and the indices(1-based indexing) of elements in the original array if it exists. Prerequisites: Pigeonhole PrincipleExamples: Input: arr[] = { 2, 3, 7, 1, 9 } Output: 2 1 2 The req
8 min read
Split Array into K non-overlapping subset such that maximum among all subset sum is minimum
Given an array arr[] consisting of N integers and an integer K, the task is to split the given array into K non-overlapping subsets such that the maximum among the sum of all subsets is minimum. Examples: Input: arr[] = {1, 7, 9, 2, 12, 3, 3}, M = 3Output: 13Explanation:One possible way to split the array into 3 non-overlapping subsets is {arr[4],
7 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[] = {3, 7, 6}Output: PossibleNot PossiblePossibleEx
10 min read
Largest possible Subset from an Array such that no element is K times any other element in the Subset
Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum size of a subset possible such that no element in the subset is K times any other element of the subset(i.e. no such pair {n, m} should be present in the subset such that either m = n * K or n = m * K). Examples: Input: arr[] = {2, 8, 6, 5, 3},
7 min read
Maximum size of subset such that product of all subset elements is a factor of N
Given an integer N and an array arr[] having M integers, the task is to find the maximum size of the subset such that the product of all elements of the subset is a factor of N. Examples: Input: N = 12, arr[] = {2, 3, 4}Output: 2Explanation: The given array 5 subsets such that the product of all elements of the subset is a factor of 12. They are {2
6 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 = 30Output: []Explanation: There is no subset that
8 min read
Subset Sum Problem
Given a 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[] = {3, 34, 4, 12, 5, 2}, sum = 30Output: FalseExplanation: There is no
30 min read