Subarray Sums Divisible by K in C++

C++Server Side ProgrammingProgramming

Suppose we have an array A of integers. We have to find the number of contiguous non-empty subarray, that have a sum divisible by k. If A = [4,5,0,-2,-3,1] and k = 5, then the output will be 7. There are seven subarrays. [[4,5,0,-2,-3,1], [5], [5,0],[5,0,-2,-3], [0], [0,-2,-3], [-2,-3]]

To solve this, we will follow these steps −

  • make one map m and set m[0] as 1
  • temp := 0, ans := 0, and n := size of array a
  • for i in range 0 to n – 1
    • temp := temp + a[i]
    • x := (temp mod k + k) mod k
    • ans := ans + m[x]
    • increase m[x] by 1
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int subarraysDivByK(vector<int>& a, int k) {
      unordered_map <int, int> m;
      m[0] = 1;
      int temp = 0;
      int ans = 0;
      int n = a.size();
      for(int i = 0; i < n; i++){
         temp += a[i];
         int x = (temp % k + k) % k;
         ans += m[x];
         m[x]++;
      }
      return ans;
   }
};
main(){
   vector<int> v = {4,5,0,-2,-3,1};
   Solution ob;
   cout <<(ob.subarraysDivByK(v, 5));
}

Input

[4,5,0,-2,-3,1]
5

Output

7
raja
Published on 30-Apr-2020 07:41:52
Advertisements