Count subarrays whose sum is divisible by k
Given an integer array nums (values may be negative) and a positive integer k, count the number of contiguous subarrays whose sum is divisible by k.
nums = [4, 5, 0, -2, -3, 1], k = 5
-> 7
Target time.
Show a hint
A subarray (j, i] sums to a multiple of k exactly when the two prefix sums P[i] and P[j] leave the same remainder mod k. How many earlier prefixes share the current remainder?
Your answer
This one is open-ended. Work it through, then check your reasoning against the full solution.