![]() |
VOOZH | about |
Given an integer array arr[] and an integer k, find the total number of contiguous subarrays whose sum is divisible by k.
Examples:
Input: arr[] = [4, 5, 0, -2, -3, 1], k = 5
Output: 7
Explanation: There are 7 subarrays whose sum is divisible by 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3] and [-2, -3].Input: arr[] = [2, 2, 2, 2, 2, 2], k = 2
Output: 21
Explanation: All subarray sums are divisible by 2.Input: arr[] = [-1, -3, 2], k = 5
Output: 0
Explanation: There is no subarray whose sum is divisible by 5.
Table of Content
The idea is to iterate over all possible subarrays while maintaining their sum. Whenever the sum is divisible by
k, increment the count.
7
The idea is to use Prefix Sum Technique along with Hashing. On observing carefully, we can say that if a subarray arr[i...j] has sum divisible by k, then (prefix sum[i] % k) will be equal to the (prefix sum[j] % k). So, we can iterate over arr[] while maintaining a hash map or dictionary to count the number of (prefix sum mod k). For each index i, the number of subarrays ending at i and having sum divisible by k will be equal to the count of occurrences of (prefix sum[i] mod k) before i.
Note: Negative value of (prefix sum mod k) needs to be handled separately in languages like C++, Java, C# and JavaScript, whereas in Python (prefix sum mod k) is always a non-negative value as it takes the sign of the divisor, that is k.
7
Time Complexity: O(n), as we are iterating over the array only once.
Auxiliary Space: O(min(n, k)), as at most k keys can be present in the hash map or dictionary.