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 the number of subarrays in an array whose sum is divisible by a given integer K.

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

  • Use a hashmap to store the frequency of remai...read more

Help your peers!
Select
Add answer anonymously...

SPRINKLR Full Stack Engineer interview questions & answers

A Full Stack Engineer was asked Q. Rank from Stream Problem Statement Given an array of integers ARR and an integer...read more
A Full Stack Engineer was asked Q. Smaller Elements Count Problem Statement Given an array of size N, return a coun...read more
A Full Stack Engineer was asked Q. Minimum Operations to Equalize Array Given an integer array ARR of length N wher...read more

Popular interview questions of Full Stack Engineer

A Full Stack Engineer was asked Q1. Rank from Stream Problem Statement Given an array of integers ARR and an integer...read more
A Full Stack Engineer was asked Q2. Smaller Elements Count Problem Statement Given an array of size N, return a coun...read more
A Full Stack Engineer was asked Q3. Minimum Operations to Equalize Array Given an integer array ARR of length N wher...read more
SPRINKLR Full Stack Engineer 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