Remainder counts
Time O(n) Space O(k)count[0] = 1. For each prefix remainder r (made non-negative), add count[r], then count[r]++.
nums = [4,5,0,-2,-3,1], k = 5remainder counts(map)
state(vars)
Step 1/5Before any number the sum is 0, so remainder 0 has been seen once.
class Solution {
public int subarraysDivByK(int[] nums, int k) {
int[] count = new int[k];
count[0] = 1;
int sum = 0, total = 0;
for (int x : nums) {
sum += x;
int r = ((sum % k) + k) % k;
total += count[r];
count[r]++;
}
return total;
}
}Verdict: Subarray Sum Equals K with remainders instead of values.