Subarray Sum Divisible By K Problem
Description
LeetCode Problem 974. Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum is divisible by k.
Example:
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]
Solution
Approach: Prefix Sums and Remainder Counts
Checking every subarray takes O(n2) time. Prefix sums reduce it to one pass.
Let prefix[i] be the sum of the first i numbers. The subarray nums[i..j] has sum prefix[j + 1] - prefix[i], and that difference is divisible by k exactly when the two prefix sums have the same remainder modulo k. So the answer is the number of pairs of prefixes with equal remainders.
Count them in one pass:
- Keep
count[r], the number of prefixes seen so far with remainderr. Start withcount[0] = 1for the empty prefix, so subarrays that start at index 0 are counted. - For each number, update the running remainder, add
count[remainder]to the answer (each of those earlier prefixes ends a valid subarray here), then incrementcount[remainder].
Example with nums = [4,5,0,-2,-3,1], k = 5: the remainders after each number are 4, 4, 4, 2, 4, 0. The answer adds 0 + 1 + 2 + 0 + 3 + 1 = 7.
The classic bug is negative numbers. In Java, C++, JavaScript and Go, -2 % 5 is -2, not 3, so a prefix with sum -2 would not match one with sum 3 even though their difference 5 is divisible by 5. Use ((remainder + x) % k + k) % k to keep remainders in [0, k). Python's % is already non-negative.
Complexity: O(n + k) time and O(k) space, where n is the length of nums.
class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
# count[r] = how many prefixes so far have a sum with remainder r modulo k
count = [0] * k
count[0] = 1 # the empty prefix
remainder = 0
result = 0
for x in nums:
remainder = (remainder + x) % k # Python's % is never negative
result += count[remainder] # each earlier prefix with the same remainder ends a valid subarray here
count[remainder] += 1
return result
Now write it from memory
Close the write-up and solve it yourself against the tests.