In this video, we will explore how to count the number of subarrays whose sum is divisible by a given integer k. We begin by discussing the naive approach, which iterates over all possible subarrays while tracking the sum modulo k. If the sum modulo k is zero, it means the subarray sum is divisible by k. We then calculate the result by checking every subarray in the array, which results in a time complexity of O(n^2).
Next, we introduce an optimized approach using the Prefix Sum modulo k technique along with Hashing. In this approach, we maintain a prefix sum and use a hash map to count the occurrences of each prefix sum modulo k. If the prefix sum modulo k equals zero, the subarray starting from the beginning to that index is divisible by k. We further optimize this by handling negative prefix sums appropriately, achieving a time complexity of O(n) and auxiliary space of O(min(n, k)). This approach significantly reduces the time complexity and provides a more efficient solution to the problem.
For more details, please go through - Count Subarrays With Sum Divisible By K