![]() |
VOOZH | about |
Given an array arr[] of N integers, your task is to count the number of subarrays where the sum of values is divisible by N.
Examples:
Input: N = 5, arr[] = {3, 1, 2, 7, 4}
Output: 1
Explanation: There is only 1 subarray with sum divisible by 5, subarray {1, 2, 7}, sum = 10 and 10 is divisible by 5.Input: N = 5, arr[] = {1, 2, 3, 4, 5}
Output: 4
Explanation: There are 4 subarrays with sum divisible by 5
- Subarray {5}, sum = 5 and 5 is divisible by 5.
- Subarray {2, 3}, sum = 5 and 5 is divisible by 5.
- Subarray {1, 2, 3, 4}, sum = 10 and 10 is divisible by 5.
- Subarray {1, 2, 3, 4, 5}, sum = 15 and 15 is divisible by 5.
Approach: To solve the problem, follow the below idea:
The problem is similar to Subarray Sums II. We can maintain a Map, that stores the (prefix sums % N) along with the number of times they have occurred. At any index i, let's say (prefix sums % N) = R, that is (sum of subarray arr[0...i] % N) = R. Now if there is an index j (j < i) such that (sum of subarray arr[0...j] % N) = R, then the remainder of subarray arr[j+1...i] will be equal to 0, which means that the subarray arr[j+1...i] is divisible by N. Therefore, for every index i, if we can find the count of prefixes before i which have remainder as arr[0...i], we can add the count to our answer and the sum of count for all indices will be the final answer.
This allows us to find a subarray within our current array (by removing a prefix from our current prefix) that leaves remainder = 0, when divided by N. Also, as we iterate through the array, we continuously update the map with the new remainders after each step so that all possible remainders are counted in the map as we traverse the array.
Step-by-step algorithm:
Below is the implementation of the above algorithm:
4
Time Complexity: O(N * logN), where N is the size of arr[].
Auxiliary Space: O(N)