Subarray Sum Divisibility
UptoSkills Arena is hosting a coding competition, and you're tasked with a crucial preprocessing step: finding subarrays whose sum is divisible by a given number k.
Your program will receive an array of n integers. You need to count how many contiguous subarrays have a sum that is exactly divisible by k. A subarray is defined by its start and end indices. Remember, a subarray of length 1 is also a valid subarray.
Input
The first line contains two integers, n and k.
The second line contains n integers, the elements of the array.
Output
A single integer representing the count of subarrays whose sum is divisible by k.
Constraints
1 <= n <= 200000 1 <= k <= 200000 -10^9 <= arr[i] <= 10^9
Example 1
5 3 4 5 0 -2 -3
6
Subarrays: [3], [0], [-2, -3], [4, 5, 0, -2, -3], [5, 0, -2], [0, -2, -3], [4, 5, 0]. Sums: 3, 0, -5, 4, 3, 0, 9. Divisible by 3: 3, 0, 3, 0, 9. There are 7 such subarrays.
Example 2
4 5 5 5 5 5
10
All subarrays have sums divisible by 5. Total subarrays: n*(n+1)/2 = 4*5/2 = 10.
Hints
Similar problems
- Longest Subarray with Equal Number of Zeroes and OnesHard
- Longest Prefix with Equal CountsMedium
- Count Subarrays with Distinct ElementsMedium
- Kiran's Cool CollectionsMedium
- Sort by Subsequence SumMedium
- Longest Subarray with At Most K Distinct ElementsMedium
More topics: Hash Map and Hashing problems, Two Pointers problems, Prefix Sums problems
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
5 3 4 5 0 -2 -3
4 5 5 5 5 5