 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Subarray Sums Divisible by K in C++
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
#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
Advertisements
 