VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-subarray-divisibility/

⇱ CSES Solutions - Subarray Divisibility - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Subarray Divisibility

Last Updated : 23 Jul, 2025

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:

  • Maintain a map, say remaindersCnt to store the count of occurrences of each (prefix sum % N).
  • Maintain a variable remainder = 0, to calculate the remainder of prefix sum till any index and a variable cnt = 0 to count the number of subarrays with prefix sum divisible by N.
  • Initialize remaindersCnt[0] = 1 so when we get any subarray with sum divisible by N, we can add remaindersCnt[pref % N] = remaindersCnt[0] = 1 to the answer.
  • Iterate over all the elements arr[i],
    • Store the remainder of prefix sums of subarray arr[0...i] into remainder.
    • Add the frequency of remaindersCnt[remainder] to the cnt.
    • Increment the frequency of remainder by 1.
  • Return the final answer as cnt.

Below is the implementation of the above algorithm:


Output
4

Time Complexity: O(N * logN), where N is the size of arr[].
Auxiliary Space: O(N)

Comment
Article Tags:
Article Tags: