Subset Sum Problem in O(sum) space
Last Updated :
16 May, 2024
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
?>
OutputThere 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>
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.
Equal Sum Partition | DSA 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