Sub-Array sum divisible by K | Practice | GeeksforGeeks

You are given an array A of N positive and/or negative integers and a value K. The task is to find the count of all sub-arrays whose sum is divisible by K.
Example 1:
Input: N = 6, K = 5
       arr[] = {4, 5, 0, -2, -3, 1}
Output: 7
Explanation: There are 7 sub-arrays whose 
is divisible by K {4, 5, 0, -2, -3, 1}, {5}, 
{5, 0}, {5, 0, -2, -3}, {0}, {0, -2, -3} 
and {-2, -3}

Example 2:
Input: N = 6, K = 2
       arr[] = {2, 2, 2, 2, 2, 2}
Output: 21
Explanation: All subarray sums are 
divisible by 7


 
Your Task:
This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function subCount() that takes array arr, integer N, and integer K as parameters and returns the desired output.
Expected Time Complexity: O(N+K).
Expected Auxiliary Space: O(K).
 
Constraints:
2 ≤ N ≤ 105
 
+1
abhishekshrivastav19201 month ago
not easy problem if you have to solve in O(N).
0
rajubugude3 months ago
PYTHON (Prefix Sum + Hash map)
Total Time Taken: 0.8/5.8
class Solution:
    def subCount(self,arr, n, k):
        # Your code goes here
        res = {0:1} #coz len of arr >= 2
        summ = 0
        count = 0
        for i in range(n):
            summ += arr[i]
            rem = summ % k
            # If rem already in 'remMap'.
            if(rem in res):
                count += res[rem]
                res[rem] += 1
            else:
                res[rem] = 1
        return count
+1
aloksinghbais023 months ago
C++ solution having time complexity as O(N) and space complexity as O(N) is as follows :-
 
Execution Time :- 0.7 / 1.7 sec
 
long long subCount(long long arr[], int n, long long k){    long long int cnt = 0;    unordered_map<long long int,int> mp;        long long int currSum = 0; mp[0]++;    for(int i=0; i<n; i++){        currSum += arr[i];        int rem = currSum % k;        if(rem < 0) rem = rem + k;        if(mp.find(rem) != mp.end()){            cnt += mp[rem];        }        mp[rem]++;    }    return (cnt);}
0
chessnoobdj3 months ago
C++
long long subCount(long long arr[], int N, long long K)
	{
	    long long pref = 0; // prefix sum
        vector<long long> cPref(K); //sum will not exceed K as we are taking modulo at every step
        cPref[pref]++; // adding 0 as prefix sum, base case
        
        int answer = 0; // count of number of subarrays whose sum is divisible by K
        
        for(int i=0; i<N; i++) {
            
            pref = (pref + arr[i]) % K; // Here, we take modulo of prefix sum as outlined in the explanation
            
            if(pref < 0) pref += K; // since -1 mod 5 and 4 mod 5 are equivalent, we will keep only positives since we like them :)
                        
            answer += cPref[pref]; // if we have already found pref, then increase the answer count
            
            cPref[pref]++; // add pref seen count by 1
        }
        
        return answer;
	}
0
radheshyamnitj4 months ago
 unordered_map<int,int> mp;    int ans=0,cursum=0;    mp[0]=1;    int rem=0;    for(int i=0;i<N;i++){        cursum+=arr[i];        rem=cursum%K;        if(rem<0){            rem+=K;        }        if(mp.find(rem)!=mp.end()){            ans+=mp[rem];        }        mp[rem]++;    }    return ans;    }
+1
badgujarsachin834 months ago
long long subCount(long long arr[], int N, long long K)
	{
	    // Your code goes here
	    unordered_map<int,int> mp;
	    int ans=0,cursum=0;
	    mp[0]=1;
	    int rem=0;
	    for(int i=0;i<N;i++){
	        cursum+=arr[i];
	        rem=cursum%K;
	        if(rem<0){
	            rem+=K;
	        }
	        if(mp.find(rem)!=mp.end()){
	            ans+=mp[rem];
	            mp[rem]++;
	        }
	        else{
	            mp[rem]++;
	        }
	    }
	    return ans;
	}
0
Rahul Kumar8 months ago
Rahul Kumar
Pepcoding tutorial, in case you are stuck
-1
shahzdor9 months ago
shahzdor
Python solution:
class Solution:  def subCount(self,arr, n, k):    dict1=dict({0:1})    sum1=0    count=0    for i in range(n):      sum1+=arr[i]      x=(sum1%k)
      if x not in dict1:        dict1[x]=1
      else:        dict1[x]+=1        count+=dict1[x]-1
    return count
0
Shreyansh Kumar Singh10 months ago
Shreyansh Kumar Singh
This is a Leetcode Medium level question but it's marked Easy here.  Leetcode 974. Subarray Sums Divisible by K
-1
Soumya Sharma10 months ago
Soumya Sharma
EXECUTION TIME = 0.61 s
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.