Subset with sum divisible by m | Practice | GeeksforGeeks

Given a set of n non-negative integers, and a value m, determine if there is a subset of the given set with sum divisible by m.
Example 1:
Input: 
n = 4 m = 6 
nums[] = {3 1 7 5}
Output:
1
Explanation:
If we take the subset {7, 5} then sum
will be 12 which is divisible by 6.

Example 2:
Input:
n = 3, m = 5
nums[] = {1 2 6}
Output:
0
Explanation: 
All possible subsets of the given set are 
{1}, {2}, {6}, {1, 2}, {2, 6}, {1, 6}
and {1, 2, 6}. There is no subset whose
sum is divisible by 5.

Your Task:
You don't need to read or print anything. Your task is to complete the function DivisibleByM() which takes the given set and m as input parameter and returns 1 if any of the subset(non-empty) sum is divisible by m otherwise returns 0.
Expected Time Complexity: O(n*m)
Expected Space Complexity: O(n)
Constraints:
1 <= elements in set <= 1000
1 <= n, m <= 1000
0
imranwahid1 week ago
Easy C++ solution using memoization
0
_luffy_2 months ago
int sum =0;
		    for(auto v:nums)
		        sum+=v;
		       
		    bool dp[2][sum+1];
		    for(int i=0;i<=nums.size();i++)
		    {
		        for(int j=0;j<=sum;j++)
		        {
		            if(j==0)
		                dp[i%2][j] = true;
		            else if(i==0)
		                dp[0][j] = false;
		            else if(nums[i-1] <= j)
		                dp[i%2][j] = dp[1 - i%2][j- nums[i-1]] || dp[1 - i%2][j];
		            else
		                dp[i%2][j] = dp[1 - i%2][j];
		        }
		    }
		    for(int i=m;i<=sum;i+=m)
		        if(dp[nums.size()%2][i])
		        {
		            return 1;
		        }
		  
		   return 0;
0
ayushshaw13 months ago
Simple recursive solution in java
// { Driver Code Starts//Initial Template for Java
import java.util.*;import java.lang.*;import java.io.*;class GFG{   public static void main(String[] args) throws IOException   {       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));       int T = Integer.parseInt(br.readLine().trim());       while(T-->0)       {           String a = br.readLine().trim();           String[] a1 = a.split(" ");           int n = Integer.parseInt(a1[0]);           int m = Integer.parseInt(a1[1]);           String b = br.readLine().trim();           String[] b1 = b.split(" ");           int[] nums = new int[n];           for(int i = 0; i < b1.length; i++)               nums[i] = Integer.parseInt(b1[i]);           Solution ob = new Solution();           int ans = ob.DivisibleByM(nums, m);           System.out.println(ans);                   }   }}// } Driver Code Ends
//User function Template for Java
class Solution{   int A[];   int mod;   boolean ans  =false;   public int DivisibleByM(int [] nums, int m)   {       // Code here       A=nums;       mod=m;       Check(0,0,true);       if(ans)       return(1);       else       return(0);   }   public void Check(int prev_sum, int i,boolean empty){       if(i==A.length || ans){           if(prev_sum==0 && !empty)           ans=true;           return;       }       else{           if(prev_sum==0 && !empty){               ans=true;               return;           }           else{               Check(prev_sum,i+1,empty);
           }           prev_sum=(prev_sum+A[i])%mod;           if(prev_sum==0)           {               ans=true;               return;           }           Check(prev_sum,i+1,false);
       }   }   }
0
aaravarya14 months ago
C++ simple recursive solution in 0.0 time
  bool solve(vector<int> nums, int m, int sum, int end)        {            if(sum%m == 0 && sum!=0) return true;            if(end<0) return false;                        else               return solve(nums, m, sum, end-1) ||                solve(nums, m , sum+nums[end], end-1);        } int DivisibleByM(vector<int>nums, int m){     // Code here     int len=nums.size();     if(solve(nums, m, 0, len-1 )) return 1;     else return 0; }
 
0
soumo2k154 months ago
int fnc(vector<int>a,int n,int k,int sum,vector<vector<int>>&dp){           if(sum && sum%k==0)return 1;           if(n<=0)return 0;           if(dp[n][sum]!=-1)return dp[n][];           dp[n][sum] = fnc(a,n-1,k,sum+a[n-1],dp)+fnc(a,n-1,k,sum,dp);           return dp[n][sum];       } int DivisibleByM(vector<int>v, int k){     int n=v.size();     vector<vector<int>>dp(n+1,vector<int>(1003,-1));     if (fnc(v,n,k,0,dp))return 1;     return 0; }
+1
pereiraripson5 months ago
man the brute force totally got accepted, i used 3 nested for loops
0
shrish9 months ago
shrish
USING BITSET (WITHOUT DP  SOLN)-> if you don't know bitset please learn it from youtube or errictto's blog
soln link
int DivisibleByM(vector<int>nums, int m){    bitset<10000>b;     b[0] = 1;     for(auto a:nums)    b|=(b<<a); int="" c="0;" for(int="" i="1;i&lt;10000;i++)" if(i%m="=0" &&="" b[i]="=1)" return="" 1;="" return="" 0;="" }="" <="" code="">
0
Dhananjay Singh9 months ago
Dhananjay Singh
class Solution{    public int find(int nums[],int n,int m,int sum,int arr[]){
        if((sum%m)==0 && sum!=0)return 1;        else if(n==0)return 0;        else if(arr[(sum%m)]!=-1)return arr[(sum%m)];
        else return arr[(sum%m)]=(find(nums,n-1,m,sum+nums[n-1],arr) | find(nums,n-1,m,sum,arr));    }    public int DivisibleByM(int [] nums, int m)    {
        int n= nums.length;        int arr[]=new int[m];        Arrays.fill(arr,-1);
        return find(nums,n,m,0,arr);    }}
0
Saubhik Kumar11 months ago
Saubhik Kumar
O(nlogm) time and O(n) space approach .We can use set to store the mod of prefix sum till ith element, and check if the same mod value was there till jth element where j<i. this="" can="" be="" found="" in="" o(logm)="" using="" set.="" <code="">int DivisibleByM(vector<int>nums, int m){    // Code here    vector<int> presums;    set<int> st;    for(int i=0;i<nums.size();i++) {="" if(i="=0)" presums.push_back(nums[0]%m);="" else="" presums.push_back((presums[i-1]+nums[i])%m);="" }="" for(int="" ch="" :="" presums)="" {="" cout<<ch<<endl;="" if(ch="=0)" return="" 1;="" if(st.count(ch))="" return="" 1;="" st.insert(ch);="" }="" return="" 0;="" }="" <="" code="">
0
yash garala1 year ago
yash garala
Simple Solution int DivisibleByM(vector<int>nums, int m){    int n=nums.size();    map<int,int> arr;    int ans=0;    int sum=0;    arr[0]=1;    for(int i=0;i<n;i++) {="" sum+="nums[i];" int="" temp="sum%m;" if(arr[temp]="=0)" {="" arr[temp]="1;" }="" else="" {="" arr[temp]+="1;" ans+="arr[temp];" }="" }="" if(ans="=0" )="" {="" return="" 0;="" }="" else="" return="" 1;="" code="" here="" }="" <="" code="">
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.