Subset sum problem where Array sum is at most N
Last Updated :
23 Jul, 2025
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:
Possible
Not Possible
Possible
Explanation: 3 is spossible. 6 can be obtained by the subset {1, 2, 3}
7 is greater than the sum of all array elements.
Input: arr[] = {0, 1, 2}, queries[] = {1, 2, 3, 0}
Output:
Possible
Possible
Possible
Possible
Explanation: All the sums can be obtained by using the elements.
Approach: The problem can be solved using the approach as in the subset sum problem.
However, the time complexity can be reduced using the fact that the sum can be at most N. As the sum can be at most N, it can be proved that there are at most √2N unique positive elements where all have a frequency of 1.
Say there are √2N unique positive elements starting from 1 to √2N.
Therefore the sum of those numbers is N + √(N/2).
This sum is more than N itself. So there can be at most √2N unique elements.
The above fact can be used and implemented in dynamic programming. Using coordinate compression all those unique elements can be stored in minimum space.
For each element check what is the minimum contribution of that element to achieve a sum j (j in the range [0, N]) or if it is not possible to achieve the sum j. The contribution of each item (say i) depends on the contribution of the other smaller items till the sum (j - i).
Follow the image shown below to understand better the difference of unused states for normal subset and when the sum is N at max:
Comparison:
Say the arr[] = {1, 2, 2, 2, 3, 3}. (Here sum is greater, so does not follow the condition of sum at most N. But here unique elements maintain the threshold. That's why it is used here just for understanding purpose)
Red cells signify the useless states, these are much more in traditional algorithm than optimized one.
Traditional Subset-Sum vs Frequency Optimized DP, Useless States
Follow the steps mentioned below to implement the approach;
- Use coordinate compression on all the unique elements.
- Build a 2D dp[][] array where dp[i][j] stores the contribution of ith item to get sum j. (If it is not possible then store -1, and if ith item is not needed then store 0 in dp[i][j]).
- Iterate from i = 0 to the maximum element:
- Iterate for j = 0 to N:
- If the value of dp[i][j-arr[i]] + 1 < dp[i][j] then update it.
- Otherwise, keep it as it was.
- Then iterate from i = 0 to Q:
- Check if that sum (query[i])is possible or not.
- It is not possible if it exceeds the array sum or all the elements together cannot get a certain sum i.e. dp[len][query[i]] = -1. (len is total number of unique elements)
Below is the implementation of the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find if the queries
// are possible or not
void findSol(vector<int>& arr,
vector<int>& queries)
{
int s = 0;
// Calculating sum of array
for (auto& item : arr) {
s += item;
}
// Coordinate compression,
// make frequency-value pairs
map<int, int> mp;
for (auto& item : arr) {
mp[item]++;
}
vector<int> val, freq;
// Frequency mapping
for (auto& x : mp) {
val.push_back(x.first);
freq.push_back(x.second);
}
int len = val.size();
vector<vector<int> > dp(len + 1,
vector<int>(
s + 1, 0));
for (int j = 1; j <= s; ++j) {
dp[0][j] = -1;
}
// Loop to build the dp[][]
for (int i = 1; i <= len; ++i) {
for (int j = 1; j <= s; ++j) {
int v = val[i - 1];
int f = freq[i - 1];
if (dp[i - 1][j] != -1) {
dp[i][j] = 0;
}
else if (j >= v
&& dp[i][j - v] != -1
&& dp[i][j - v] + 1 <= f) {
dp[i][j] = dp[i][j - v] + 1;
}
else {
dp[i][j] = -1;
}
}
}
// Answer queries
for (auto& q : queries) {
if (q > s || dp[len][q] == -1) {
cout << "Not Possible" << endl;
}
else {
cout << "Possible" << endl;
}
}
}
// Driver Code
int main()
{
vector<int> arr = { 1, 0, 0, 0, 0, 2, 3 };
vector<int> queries = { 3, 7, 6 };
// Function call
findSol(arr, queries);
return 0;
}
Java
// Java code to implement the approach
import java.util.*;
class GFG
{
// Function to find if the queries
// are possible or not
static void findSol(ArrayList<Integer> arr, ArrayList<Integer> queries)
{
int s = 0;
// Calculating sum of array
for (Integer item : arr) {
s += item;
}
// Coordinate compression,
// make frequency-value pairs
HashMap<Integer, Integer> mp = new HashMap<>();
for (Integer item : arr) {
if(mp.containsKey(item))
mp.put(item,mp.get(item)+1);
else
mp.put(item,1);
}
ArrayList<Integer> val = new ArrayList<Integer>();
ArrayList<Integer> freq = new ArrayList<Integer>();
// Frequency mapping
for (Map.Entry<Integer,Integer> x : mp.entrySet())
{
val.add(x.getKey());
freq.add(x.getValue());
}
int len = val.size();
int dp[][] = new int[len+1][s+1];
for (int j = 1; j <= s; ++j) {
dp[0][j] = -1;
}
// Loop to build the dp[][]
for (int i = 1; i <= len; ++i) {
for (int j = 1; j <= s; ++j) {
int v = val.get(i - 1);
int f = freq.get(i - 1);
if (dp[i - 1][j] != -1) {
dp[i][j] = 0;
}
else if (j >= v
&& dp[i][j - v] != -1
&& dp[i][j - v] + 1 <= f) {
dp[i][j] = dp[i][j - v] + 1;
}
else {
dp[i][j] = -1;
}
}
}
// Answer queries
for(Integer q:queries)
{
if (q > s || dp[len][q] == -1) {
System.out.println("Not Possible");
}
else {
System.out.println("Possible");
}
}
}
// Driver Code
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<Integer>(
Arrays.asList(1, 0, 0, 0, 0, 2, 3 ));
ArrayList<Integer> queries = new ArrayList<Integer>(
Arrays.asList(3, 7, 6 ));
// Function call
findSol(arr, queries);
}
}
// This code is contributed by Pushpesh Raj.
Python3
# Python3 code to implement the approach
# Function to find if the queries
# are possible or not
def findSol(arr, queries):
# calculating sum of array
s = sum(arr)
# Coordinate compression,
# make frequency-value pairs
mp = dict()
for item in arr:
if item not in mp:
mp[item] = 1
else:
mp[item] += 1
val = []
freq = []
# Frequency mapping
for x in mp:
val.append(x)
freq.append(mp[x])
len_ = len(val)
dp = [[0 for i in range(s + 1)] for j in range(len_ + 1)]
for j in range(1, s + 1):
dp[0][j] = -1
# Loop to build dp[][]
for i in range(1, len_ + 1):
for j in range(1, s + 1):
v = val[i - 1]
f = freq[i - 1]
if dp[i - 1][j] != -1:
dp[i][j] = 0
elif j >= 0 and dp[i][j - v] != -1 and dp[i][j - v] + 1 <= f:
dp[i][j] = dp[i][j - v] + 1
else:
dp[i][j] = -1
# Answer queries
for q in queries:
if q > s or dp[len_][q] == -1:
print("Not Possible")
else:
print("Possible")
# Driver Code
arr = [1, 0, 0, 0, 0, 2, 3]
queries = [3, 7, 6]
# Function call
findSol(arr, queries)
# This code is contributed by phasing17
C#
// C# program to implement above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to find if the queries
// are possible or not
public static void findSol(List<int> arr, List<int> queries)
{
int s = 0;
// Calculating sum of array
foreach (int item in arr){
s += item;
}
// Coordinate compression,
// make frequency-value pairs
SortedDictionary<int, int> mp = new SortedDictionary<int, int>();
foreach (int item in arr) {
if(mp.ContainsKey(item)){
mp[item] = mp[item] + 1;
}else{
mp.Add(item, 1);
}
}
List<int> val = new List<int>();
List<int> freq = new List<int>();
// Frequency mapping
foreach (KeyValuePair<int,int> x in mp)
{
val.Add(x.Key);
freq.Add(x.Value);
}
int len = val.Count;
int[,] dp = new int[len+1, s+1];
for (int j = 1; j <= s; ++j) {
dp[0, j] = -1;
}
// Loop to build the dp[][]
for (int i = 1; i <= len; ++i) {
for (int j = 1; j <= s; ++j) {
int v = val[i - 1];
int f = freq[i - 1];
if (dp[i - 1, j] != -1) {
dp[i, j] = 0;
}
else if (j >= v && dp[i, j - v] != -1 && dp[i, j - v] + 1 <= f) {
dp[i, j] = dp[i, j - v] + 1;
}
else{
dp[i, j] = -1;
}
}
}
// Answer queries
foreach(int q in queries)
{
if (q > s || dp[len, q] == -1) {
Console.Write("Not Possible\n");
}
else {
Console.Write("Possible\n");
}
}
}
// Driver Code
public static void Main(string[] args){
List<int> arr = new List<int>{
1, 0, 0, 0, 0, 2, 3
};
List<int> queries = new List<int>{
3, 7, 6
};
// Function call
findSol(arr, queries);
}
}
// This code is contributed by subhamgoyal2014.
JavaScript
<script>
// JavaScript code to implement the approach
// Function to find if the queries
// are possible or not
function findSol(arr,queries)
{
let s = 0;
// Calculating sum of array
for (let item of arr) {
s += item;
}
// Coordinate compression,
// make frequency-value pairs
let mp = new Map();
for (let item of arr) {
if(mp.has(item))
mp.set(item,mp.get(item)+1);
else mp.set(item,1);
}
let val = [], freq = [];
// Frequency mapping
for (let [x,y] of mp) {
val.push(x);
freq.push(y);
}
let len = val.length;
let dp = new Array(len + 1).fill(0).map(()=>new Array(s+1).fill(0));
for (let j = 1; j <= s; ++j) {
dp[0][j] = -1;
}
// Loop to build the dp[][]
for (let i = 1; i <= len; ++i) {
for (let j = 1; j <= s; ++j) {
let v = val[i - 1];
let f = freq[i - 1];
if (dp[i - 1][j] != -1) {
dp[i][j] = 0;
}
else if (j >= v
&& dp[i][j - v] != -1
&& dp[i][j - v] + 1 <= f) {
dp[i][j] = dp[i][j - v] + 1;
}
else {
dp[i][j] = -1;
}
}
}
// Answer queries
for (let q of queries) {
if (q > s || dp[len][q] == -1) {
console.log("Not Possible");
}
else {
console.log("Possible");
}
}
}
// Driver Code
let arr = [ 1, 0, 0, 0, 0, 2, 3 ];
let queries = [ 3, 7, 6 ];
// Function call
findSol(arr, queries);
// This code is contributed by shinjanpatra
</script>
OutputPossible
Not Possible
Possible
Time Complexity: O(N * √N)
Auxiliary Space: O(N * √N)
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