sagelearnai

Continuous Subarray Sum

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

Given non-negative integers nums and a positive integer k, return true if there is a contiguous subarray of length at least 2 whose sum is a multiple of k (0 counts as a multiple).

Examples

text
nums = [5, 2, 4, 1], k = 6    →  true    ([2, 4] sums to 6)
nums = [5, 2, 4, 1], k = 13   →  false
nums = [3, 0, 0], k = 7       →  true    ([0, 0] sums to 0)

Hints

  1. If two prefix sums have the same remainder mod k, the subarray between them sums to a multiple of k.
  2. Store the first index where each remainder appears; the subarray needs length ≥ 2.
  3. Seed remainder 0 at index −1.

Approach

Track p mod k while scanning. Map each remainder to the earliest index where it appeared (seed {0: −1}). At index i, if remainder rem was seen at index j with i − j ≥ 2, then nums[j+1..i] has a sum divisible by k. Keep only the earliest index per remainder to maximize length.

Complexity

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

Python solution
def checkSubarraySum(nums, k):
    first = {0: -1}
    p = 0
    for i, x in enumerate(nums):
        p = (p + x) % k
        if p in first:
            if i - first[p] >= 2:
                return True
        else:
            first[p] = i
    return False
JavaScript solution
function checkSubarraySum(nums, k) {
  const first = new Map([[0, -1]]);
  let p = 0;
  for (let i = 0; i < nums.length; i++) {
    p = (p + nums[i]) % k;
    if (first.has(p)) { if (i - first.get(p) >= 2) return true; }
    else first.set(p, i);
  }
  return false;
}