result
to 0, to store the count of subarrays divisible by k
.prefixMod
to 0, to store the current prefix sum modulo k
.modGroups
of size k
to store the count of prefix sums for each possible modulo value. Set modGroups[0]
to 1.nums
.
a. Update prefixMod
with the current element's contribution: (prefixMod + nums[i] % k + k) % k
.
b. Add modGroups[prefixMod]
to result
, since this is the number of subarrays ending at the current index with a sum divisible by k
.
c. Increment modGroups[prefixMod]
by 1.result
.