sagelearnai

Subarray Sums Divisible by K

Difficulty: Medium · Pattern: Prefix Sum · LeetCode #974

Return the number of non-empty contiguous subarrays whose sum is divisible by k. Values may be negative.

Examples

text
nums = [4, 5, 0, -2, -3, 1], k = 5  →  7
nums = [5], k = 9                   →  0

Hints

  1. sum(i..j) divisible by k ⇔ P[j+1] ≡ P[i] (mod k).
  2. Count how many earlier prefixes share the current remainder.
  3. Watch out: negative numbers produce negative remainders in some languages.

Approach

Keep count[r] = how many prefix sums so far have remainder r (seed count[0] = 1). For each element, update the running remainder p = (p + x) mod k, normalized into [0, k), then add count[p] to the answer and increment count[p]. In JavaScript, % can return negatives, so use ((p % k) + k) % k.

Complexity

Time: O(n). Space: O(k).

Python solution
def subarraysDivByK(nums, k):
    count = [0] * k
    count[0] = 1
    p = ans = 0
    for x in nums:
        p = (p + x) % k                 # Python's % is already non-negative
        ans += count[p]
        count[p] += 1
    return ans
JavaScript solution
function subarraysDivByK(nums, k) {
  const count = new Array(k).fill(0); count[0] = 1;
  let p = 0, ans = 0;
  for (const x of nums) {
    p = (((p + x) % k) + k) % k;
    ans += count[p]; count[p]++;
  }
  return ans;
}