Count Distinct Subarrays Divisible by K in Sorted Array Problem
Description
LeetCode Problem 3729.
You are given an integer array nums sorted in non-descending order and a positive integer k.
A subarray of nums is good if the sum of its elements is divisible by k.
Return an integer denoting the number of distinct good subarrays of nums.
Subarrays are distinct if their sequences of values are. For example, there are 3 distinct subarrays in [1, 1, 1], namely [1], [1, 1], and [1, 1, 1].
Example 1:
Input: nums = [1,2,3], k = 3
Output: 3
Explanation:
The good subarrays are [1, 2], [3], and [1, 2, 3]. For example, [1, 2, 3] is good because the sum of its elements is 1 + 2 + 3 = 6, and 6 % k = 6 % 3 = 0.
Example 2:
Input: nums = [2,2,2,2,2,2], k = 6
Output: 2
Explanation:
The good subarrays are [2, 2, 2] and [2, 2, 2, 2, 2, 2]. For example, [2, 2, 2] is good because the sum of its elements is 2 + 2 + 2 = 6, and 6 % k = 6 % 6 = 0.
Note that [2, 2, 2] is counted only once.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9numsis sorted in non-descending order.1 <= k <= 10^9
Solution
Approach: Prefix Sums Modulo k, Then Remove Duplicates
First count all subarrays (ignoring duplicates) whose sum is divisible by k: keep the prefix sum modulo k and a hash table of how many times each remainder has appeared; every earlier prefix with the same remainder gives one good subarray.
Because the array is sorted, two different subarrays can have the same sequence of values only when they lie inside the same run of equal numbers. Take a run of m equal values v. A subarray of length h inside it is good when h * v is divisible by k, and there are m - h + 1 such subarrays but only one distinct sequence, so subtract m - h for each such h from 1 to m.
Complexity: time O(n), space O(n), where n is the length of the array (the work over all runs adds up to n).
class Solution:
def numGoodSubarrays(self, nums: List[int], k: int) -> int:
cnt = Counter({0: 1})
ans = s = 0
for x in nums:
s = (s + x) % k
ans += cnt[s]
cnt[s] += 1
n = len(nums)
i = 0
while i < n:
j = i + 1
while j < n and nums[j] == nums[i]:
j += 1
m = j - i
for h in range(1, m + 1):
if (h * nums[i]) % k == 0:
ans -= m - h
i = j
return ans