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.
Function Signature
def subarrays_div_by_k(nums: list[int], k: int) -> int:
Rules
-
A subarray is a non-empty run of consecutive elements
nums[i..j]
with
i <= j
.
-
Subarrays are counted by position. Two subarrays with the same values at different indices count separately.
-
A sum is divisible by
k
when it is an integer multiple of
k
. That includes 0 and negative multiples such as -5 for
k = 5
.
Constraints
-
1 <= len(nums) <= 3 * 10^4
-
-10^4 <= nums[i] <= 10^4
-
2 <= k <= 10^4
Examples
Input: nums = [4, 5, 0, -2, -3, 1], k = 5
Output: 7
The 7 subarrays with a sum divisible by 5 are [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3] and [-2, -3]. Their sums are 5, 5, 5, 0, 0, -5 and -5.
Input: nums = [5], k = 9
Output: 0
The only subarray is [5], and 5 is not divisible by 9.
Input: nums = [-1, 2, 9], k = 2
Output: 2
Of the six subarrays, only [2] (sum 2) and [-1, 2, 9] (sum 10) have an even sum. The other sums are -1, 9, 1 and 11.