Count all sub-arrays having sum divisible by k
Given an array ‘ARR’ and an integer ‘K’, your task is to find all the count of all sub-arrays whose sum is divisible by the given integer ‘K’.
Note:
If there exists no subarray in the given sequence whose sum is divisible by ‘K’ then simply return ‘0’.
Example:
Suppose the given array is ‘ARR’ = { 5, 0, 2, 3, 1} and ‘K = 5’.
As we can see in below image, there are a total of 6 subarrays that have the total sum divisible by ‘K’
So we return the integer 6.
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘2*T’ lines represent the ‘T’ test cases.
The first line of each test case contains two space-separated integers the first integer ‘N’ will denote the number of elements in the array and the second integer denotes integer ‘K’.
The second line of each test case contains ‘N’ space-separated integer that is elements of the array.
Output Format
For each test case, print an integer that is the count of all subarray that sum is divisible by ‘K’.
Note:
You are not required to print the output explicitly, it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 50
1 <= K,N <= 10^4
-10^9 <= ARR[i] <= 10^9
Time limit: 1 second
CodingNinjas
author
2y
I solved it using a hashmap. It's a pretty standard problem and can also be found easily on the internet.
CodingNinjas
author
2y
Brute Force (Time Limit Exceed)
The basic idea is that try each and every possible subarray and find the sum of the current subarray and check if the current sum is divisible by ‘K’.
- To implement this...read more
CodingNinjas
author
2y
Prefix Sum
Let’s consider the sum of subarray ( ‘i’ to ‘j’ ) is divisible by ‘K’ and we can represent the sum of a subarray ( ‘i’ to ‘j’ ) = ( subarray sum (‘0’ to ‘j’ ) - subarray sum ( ‘0’ to ‘i-1’) ...read more
CodingNinjas
author
2y
Hashing
Let’s consider the sum of subarray ( ‘i’ to ‘j’ ) is divisible by ‘K’ and we can represent the sum of a subarray ( ‘i’ to ‘j’ ) = ( subarray sum (‘0’ to ‘j’ ) - subarray sum ( ‘0’ to ‘i-1’) ). ...read more
Add answer anonymously...
Top Clearwater Analytics Software Developer interview questions & answers
Popular interview questions of Software Developer
>
Clearwater Analytics Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app