Skip to problem
←

Subarray Sums Divisible by K

Medium 0 attempts

You're given an integer array nums and an integer k. Count how many contiguous, non-empty subarrays have a sum that's evenly divisible by k.

Edge cases: A subarray summing to zero counts, since zero is divisible by any k. Watch out for negative numbers — how the remainder is computed can differ across languages.

Count subarrays by their start and end indices. Overlapping subarrays count separately, even when they contain the same values. The empty subarray never counts. For three zeros, all six nonempty subarrays have a sum divisible by any allowed k.

Function contract

Implement subarraysDivByK(nums, k).

Output: Return the number of nonempty contiguous subarrays whose sum is divisible by k.

Example 1

Input
nums = [4,5,0,-2,-3,1]
k = 5
Output
7

Example 2

Input
nums = [-1,2,9]
k = 2
Output
2
Constraints
  • 1 <= nums.length <= 3 * 10^4
  • -10^4 <= nums[i] <= 10^4
  • 2 <= k <= 10^4

Approach: Prefix Sum Remainders

If two prefix sums have the same remainder when divided by k, the subarray between them sums to a multiple of k. Count remainder frequencies as you go. Be careful with negative remainders — add k and mod again to normalize.

Seed the empty prefix with frequency 1 so subarrays starting at index 0 are counted. Count matches before recording the current prefix; reversing that order would count an empty subarray. Frequencies, rather than a set, preserve multiple valid starting indices.

javascript
function subarraysDivByK(nums, k) {
  const count = new Array(k).fill(0);
  count[0] = 1;
  let prefixSum = 0;
  let result = 0;

  for (const num of nums) {
    prefixSum += num;
    let rem = ((prefixSum % k) + k) % k;
    result += count[rem];
    count[rem]++;
  }
  return result;
}

Time Complexity: O(n + k), including initialization of the k-entry frequency array

Space Complexity: O(k)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript