CSES Solutions - Subarray Divisibility
Last Updated :
28 Mar, 2024
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:
C++
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
// Function to count the number of subarrays divisible by N
ll solve(vector<ll>& arr, ll N)
{
// Map to store the frequency of prefix sums % N
map<ll, ll> remaindersCnt;
remaindersCnt[0] += 1;
ll remainder = 0;
ll cnt = 0;
// Iterate over all the index and add the count of
// subarrays with sum divisible by N
for (int i = 0; i < N; ++i) {
// Since arr[i] can be negative, we add N to the
// remainder to avoid negative remainders
remainder = ((remainder + arr[i]) % N + N) % N;
cnt += remaindersCnt[remainder];
remaindersCnt[remainder] += 1;
}
return cnt;
}
int main()
{
// Sample Input
ll N = 5;
vector<ll> arr = { 1, 2, 3, 4, 5 };
cout << solve(arr, N);
return 0;
}
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static int GFG(int[] arr, int N) {
// Map to store the frequency of the prefix sums % N
Map<Integer, Integer> remaindersCnt = new HashMap<>();
remaindersCnt.put(0, 1);
int remainder = 0;
int cnt = 0;
for (int i = 0; i < N; ++i) {
// Since arr[i] can be negative and we add N to remainder to avoid negative remainders
remainder = ((remainder + arr[i]) % N + N) % N;
cnt += remaindersCnt.getOrDefault(remainder, 0);
remaindersCnt.put(remainder, remaindersCnt.getOrDefault(remainder, 0) + 1);
}
return cnt;
}
public static void main(String[] args) {
// Sample Input
int N = 5;
int[] arr = {1, 2, 3, 4, 5};
System.out.println(GFG(arr, N));
}
}
C#
using System;
using System.Collections.Generic;
public class Solution
{
public static int GFG(int[] arr, int N)
{
// Dictionary to store the frequency of the prefix sums % N
Dictionary<int, int> remaindersCnt = new Dictionary<int, int>();
remaindersCnt.Add(0, 1);
int remainder = 0;
int cnt = 0;
for (int i = 0; i < N; ++i)
{
// Since arr[i] can be negative and we add N to remainder to avoid negative remainders
remainder = ((remainder + arr[i]) % N + N) % N;
cnt += remaindersCnt.ContainsKey(remainder) ? remaindersCnt[remainder] : 0;
if (remaindersCnt.ContainsKey(remainder))
remaindersCnt[remainder] = remaindersCnt[remainder] + 1;
else
remaindersCnt.Add(remainder, 1);
}
return cnt;
}
public static void Main(string[] args)
{
// Sample Input
int N = 5;
int[] arr = { 1, 2, 3, 4, 5 };
Console.WriteLine(GFG(arr, N));
}
}
JavaScript
function GFG(arr, N) {
// Map to store the frequency of the prefix sums % N
let remaindersCnt = new Map();
remaindersCnt.set(0, 1);
let remainder = 0;
let cnt = 0;
for (let i = 0; i < N; ++i) {
// Since arr[i] can be negative and we add N to
// remainder to avoid negative remainders
remainder = ((remainder + arr[i]) % N + N) % N;
cnt += (remaindersCnt.get(remainder) || 0);
remaindersCnt.set(remainder, (remaindersCnt.get(remainder) || 0) + 1);
}
return cnt;
}
// Sample Input
const N = 5;
const arr = [1, 2, 3, 4, 5];
console.log(GFG(arr, N));
Python3
# Function to count the number of subarrays divisible by N
def solve(arr, N):
# Dictionary to store the frequency of prefix sums % N
remainders_cnt = {0: 1}
remainder = 0
cnt = 0
# Iterate over all the indices and add the count of
# subarrays with sum divisible by N
for i in range(len(arr)):
# Since arr[i] can be negative, we add N to the
# remainder to avoid negative remainders
remainder = ((remainder + arr[i]) % N + N) % N
cnt += remainders_cnt.get(remainder, 0)
remainders_cnt[remainder] = remainders_cnt.get(remainder, 0) + 1
return cnt
if __name__ == "__main__":
# Sample Input
N = 5
arr = [1, 2, 3, 4, 5]
print(solve(arr, N))
Time Complexity: O(N * logN), where N is the size of arr[].
Auxiliary Space: O(N)
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Dynamic Programming or DP Dynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read