Given an arrayarr[] 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>usingnamespacestd;// Function to find if the queries// are possible or notvoidfindSol(vector<int>&arr,vector<int>&queries){ints=0;// Calculating sum of arrayfor(auto&item:arr){s+=item;}// Coordinate compression,// make frequency-value pairsmap<int,int>mp;for(auto&item:arr){mp[item]++;}vector<int>val,freq;// Frequency mappingfor(auto&x:mp){val.push_back(x.first);freq.push_back(x.second);}intlen=val.size();vector<vector<int>>dp(len+1,vector<int>(s+1,0));for(intj=1;j<=s;++j){dp[0][j]=-1;}// Loop to build the dp[][]for(inti=1;i<=len;++i){for(intj=1;j<=s;++j){intv=val[i-1];intf=freq[i-1];if(dp[i-1][j]!=-1){dp[i][j]=0;}elseif(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 queriesfor(auto&q:queries){if(q>s||dp[len][q]==-1){cout<<"Not Possible"<<endl;}else{cout<<"Possible"<<endl;}}}// Driver Codeintmain(){vector<int>arr={1,0,0,0,0,2,3};vector<int>queries={3,7,6};// Function callfindSol(arr,queries);return0;}
Java
// Java code to implement the approachimportjava.util.*;classGFG{// Function to find if the queries// are possible or notstaticvoidfindSol(ArrayList<Integer>arr,ArrayList<Integer>queries){ints=0;// Calculating sum of arrayfor(Integeritem:arr){s+=item;}// Coordinate compression,// make frequency-value pairsHashMap<Integer,Integer>mp=newHashMap<>();for(Integeritem:arr){if(mp.containsKey(item))mp.put(item,mp.get(item)+1);elsemp.put(item,1);}ArrayList<Integer>val=newArrayList<Integer>();ArrayList<Integer>freq=newArrayList<Integer>();// Frequency mappingfor(Map.Entry<Integer,Integer>x:mp.entrySet()){val.add(x.getKey());freq.add(x.getValue());}intlen=val.size();intdp[][]=newint[len+1][s+1];for(intj=1;j<=s;++j){dp[0][j]=-1;}// Loop to build the dp[][]for(inti=1;i<=len;++i){for(intj=1;j<=s;++j){intv=val.get(i-1);intf=freq.get(i-1);if(dp[i-1][j]!=-1){dp[i][j]=0;}elseif(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 queriesfor(Integerq:queries){if(q>s||dp[len][q]==-1){System.out.println("Not Possible");}else{System.out.println("Possible");}}}// Driver Codepublicstaticvoidmain(String[]args){ArrayList<Integer>arr=newArrayList<Integer>(Arrays.asList(1,0,0,0,0,2,3));ArrayList<Integer>queries=newArrayList<Integer>(Arrays.asList(3,7,6));// Function callfindSol(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 notdeffindSol(arr,queries):# calculating sum of arrays=sum(arr)# Coordinate compression,# make frequency-value pairsmp=dict()foriteminarr:ifitemnotinmp:mp[item]=1else:mp[item]+=1val=[]freq=[]# Frequency mappingforxinmp:val.append(x)freq.append(mp[x])len_=len(val)dp=[[0foriinrange(s+1)]forjinrange(len_+1)]forjinrange(1,s+1):dp[0][j]=-1# Loop to build dp[][]foriinrange(1,len_+1):forjinrange(1,s+1):v=val[i-1]f=freq[i-1]ifdp[i-1][j]!=-1:dp[i][j]=0elifj>=0anddp[i][j-v]!=-1anddp[i][j-v]+1<=f:dp[i][j]=dp[i][j-v]+1else:dp[i][j]=-1# Answer queriesforqinqueries:ifq>sordp[len_][q]==-1:print("Not Possible")else:print("Possible")# Driver Codearr=[1,0,0,0,0,2,3]queries=[3,7,6]# Function callfindSol(arr,queries)# This code is contributed by phasing17
C#
// C# program to implement above approachusingSystem;usingSystem.Collections.Generic;classGFG{// Function to find if the queries// are possible or notpublicstaticvoidfindSol(List<int>arr,List<int>queries){ints=0;// Calculating sum of arrayforeach(intiteminarr){s+=item;}// Coordinate compression,// make frequency-value pairsSortedDictionary<int,int>mp=newSortedDictionary<int,int>();foreach(intiteminarr){if(mp.ContainsKey(item)){mp[item]=mp[item]+1;}else{mp.Add(item,1);}}List<int>val=newList<int>();List<int>freq=newList<int>();// Frequency mappingforeach(KeyValuePair<int,int>xinmp){val.Add(x.Key);freq.Add(x.Value);}intlen=val.Count;int[,]dp=newint[len+1,s+1];for(intj=1;j<=s;++j){dp[0,j]=-1;}// Loop to build the dp[][]for(inti=1;i<=len;++i){for(intj=1;j<=s;++j){intv=val[i-1];intf=freq[i-1];if(dp[i-1,j]!=-1){dp[i,j]=0;}elseif(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 queriesforeach(intqinqueries){if(q>s||dp[len,q]==-1){Console.Write("Not Possible\n");}else{Console.Write("Possible\n");}}}// Driver CodepublicstaticvoidMain(string[]args){List<int>arr=newList<int>{1,0,0,0,0,2,3};List<int>queries=newList<int>{3,7,6};// Function callfindSol(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 notfunctionfindSol(arr,queries){lets=0;// Calculating sum of arrayfor(letitemofarr){s+=item;}// Coordinate compression,// make frequency-value pairsletmp=newMap();for(letitemofarr){if(mp.has(item))mp.set(item,mp.get(item)+1);elsemp.set(item,1);}letval=[],freq=[];// Frequency mappingfor(let[x,y]ofmp){val.push(x);freq.push(y);}letlen=val.length;letdp=newArray(len+1).fill(0).map(()=>newArray(s+1).fill(0));for(letj=1;j<=s;++j){dp[0][j]=-1;}// Loop to build the dp[][]for(leti=1;i<=len;++i){for(letj=1;j<=s;++j){letv=val[i-1];letf=freq[i-1];if(dp[i-1][j]!=-1){dp[i][j]=0;}elseif(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 queriesfor(letqofqueries){if(q>s||dp[len][q]==-1){console.log("Not Possible");}else{console.log("Possible");}}}// Driver Codeletarr=[1,0,0,0,0,2,3];letqueries=[3,7,6];// Function callfindSol(arr,queries);// This code is contributed by shinjanpatra</script>
Output
Possible
Not Possible
Possible
Time Complexity: O(N * √N) Auxiliary Space: O(N * √N)
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
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.