Count Sub-arrays with Sum Divisible by K

Given an array ARR and an integer K, determine the number of sub-arrays in which the sum is divisible by K.

Example:

Input:
ARR = {5, 0, 2, 3, 1}, K = 5
Output:
6
Explanation:

There are 6 sub-arrays whose sum is divisible by 5.

Constraints:

  • 1 <= T <= 50
  • 1 <= K, N <= 10^4
  • -10^9 <= ARR[i] <= 10^9
  • Time limit: 1 second
Input:
First line contains integer T indicating test cases.
For each test case, first line contains N and K.
Second line has N integers for the array ARR.
Output:
Output number of sub-arrays whose sum is divisible by K for each test case.
Note:

If no subarray exists with sum divisible by K, return 0.

AnswerBot
1y

The task is to count the number of subarrays in an array whose sum is divisible by a given integer.

  • Iterate through the array and calculate the cumulative sum at each index.

  • Store the remainder of each ...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Protium Finance

Q. Search In Rotated Sorted Array Problem Statement Given a sorted array of distinc...read more
Q. What is the garbage collector in Java?
Q. What is the difference between an abstract class and an interface in Object-Orie...read more
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits