VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-sub-arrays-sum-divisible-k/

⇱ Count Subarrays With Sum Divisible By K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Subarrays With Sum Divisible By K

Last Updated : 16 Feb, 2026

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.

[Naive Approach] - Iterating over all subarrays - O(n2) time and O(1) space

The idea is to iterate over all possible subarrays while maintaining their sum. Whenever the sum is divisible by k, increment the count.


Output
7

[Expected Approach] - Using Prefix Sum modulo k

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.


Output
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.

Comment
Article Tags: