Given an integer array nums and an integer k, return the number of non-empty subarrays whose sum is divisible by k. A subarray is a contiguous part of the array.
Given an integer array nums and an integer k, return the number of non-empty subarrays whose sum is divisible by k. A subarray is a contiguous part of the array.
Example 1:
Input: {"nums":[4,5,0,-2,-3,1],"k":5}
Output: 7
Constraints:
1≤nums.length≤3×104
−104≤nums[i]≤104
2≤k≤104
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"nums":[4,5,0,-2,-3,1],"k":5}
The empty prefix has sum 0, so bucket 0 starts with one entry. Two prefixes with the same remainder mod 5 enclose a subarray whose sum is divisible by 5.
nums, with prefix mod 5 after each element
start
0
0
4
·
1
5
·
2
0
·
3
-2
·
4
-3
·
5
1
·
bottom row: prefix sum mod 5 after that element (first box is the empty prefix)
remainder buckets: count[r] = prefixes seen with remainder r