Count Subarrays with Sum Divisible by K

Given an array ARR and an integer K, your task is to count all subarrays whose sum is divisible by the given integer K.

Input:

The first line of input contains an integer T representing the number of test cases.
The next 2*T lines represent the T test cases.

For each test case:
- The first line contains two space-separated integers: N (number of elements in the array) and K.
- The second line contains N space-separated integers representing the elements of the array.

Output:

For each test case, output a single integer, the count of all subarrays whose sum is divisible by K.

Example:

Input:
ARR = [5, 0, 2, 3, 1], K = 5
Output:
6
Explanation:

There are 6 subarrays with sums divisible by K.

Constraints:

  • 1 ≤ T ≤ 50
  • 1 ≤ K, N ≤ 104
  • -109 ≤ ARR[i] ≤ 109
  • Time limit: 1 second

Note:

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

AnswerBot
4mo

Count subarrays with sum divisible by K in an array.

  • Iterate through the array and keep track of the running sum modulo K.

  • Use a hashmap to store the frequency of remainders.

  • For each prefix sum, check h...read more

Help your peers!
Select
Add answer anonymously...

Popular interview questions of Software Developer

A Software Developer was asked Q1. Next Greater Element Problem Statement Given a list of integers of size N, your ...read more
A Software Developer was asked Q2. How does Facebook store comments in its database?
A Software Developer was asked Q3. Convert a Number to Words Given an integer number num, your task is to convert '...read more
Clearwater Analytics 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