
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Subarray pairs with equal sums in JavaScript
- Smallest Integer Divisible by K in Python
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- Largest K digit number divisible by X in C++
- Count subarrays whose product is divisible by k in C++
- Find nth number that contains the digit k or divisible by k in C++
- Subarray Sum Equals K in C++
- Count all sub-arrays having sum divisible by k
- Find K Pairs with Smallest Sums in C++
- Count pairs in array whose sum is divisible by K in C++
- Subarray Product Less Than K in C++
- Python Program for Smallest K digit number divisible by X
- C++ Programming for Smallest K digit number divisible by X?
- C++ Program for Smallest K digit number divisible by X?
- C++ Program for Largest K digit number divisible by X?

Advertisements