DEV Community

Karleb
Karleb

Posted on

#974. Subarray Sums Divisible by K

https://leetcode.com/problems/subarray-sums-divisible-by-k/description/?envType=daily-question&envId=2024-06-11


/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */

var subarraysDivByK = function(nums, k) {
  let prefixMod = 0;
  let result = 0;
  const modGroups = new Array(k).fill(0);
  modGroups[0] = 1;

  for (const num of nums) {
    // Take modulo twice to avoid negative remainders.
    prefixMod = (prefixMod + num % k + k) % k;
    result += modGroups[prefixMod];
    modGroups[prefixMod]++;
  }

  return result;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)