Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.
A subarray is a contiguous part of an array.
Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by k = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
Input: nums = [5], k = 9
Output: 0
The most straightforward way to solve the problem is to consider every possible subarray of the given array. For each subarray, compute its sum and check if it’s divisible by K. This approach is simple and works fine for small input sizes.
K. If so, increment the counter.The brute force approach works but is inefficient for larger arrays. We can optimize this by leveraging the properties of prefix sums and remainders. If the prefix sum up to i is sum[0..i] and prefix sum up to j is sum[0..j], and both sum[0..i] % K and sum[0..j] % K are equal, then the subarray sum[i+1..j] is divisible by K.
We can use a HashMap to keep track of all seen remainder counts, making it easier to find the potential starting points for subarrays that end at each position in the array.
K.K.K distinct remainders.