Skip to content
DSA Patterns
Menu
Language
Prefix SumLC #5232 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Continuous Subarray Sum

Problem (restated)

Return true if nums has a contiguous subarray of length ≥ 2 whose sum is a multiple of k.

Intuition

If two prefix sums share the same mod k, the between-sum is multiple of k; require index gap ≥ 2.

Approaches

Prefix mod map

Unverified
Time O(n)Space O(min(n,k))

Idea. Map remainder → earliest index. On repeat with j-i≥2, true.

Walkthrough. [23,2,4,6,7], k=6 → subarray [2,4] works.

Trade-offs. Careful with k=0 edge (not in constraints usually k>0).

Solution
export function checkSubarraySum(nums: number[], k: number): boolean {
  const seen = new Map<number, number>([[0, -1]]);
  let sum = 0;
  for (let i = 0; i < nums.length; i++) {
    sum += nums[i]!;
    const r = k === 0 ? sum : ((sum % k) + k) % k;
    if (seen.has(r)) { if (i - seen.get(r)! >= 2) return true; }
    else seen.set(r, i);
  }
  return false;
}
export function checkSubarraySum(nums: number[], k: number): boolean {
  const seen = new Map<number, number>([[0, -1]]);
  let sum = 0;
  for (let i = 0; i < nums.length; i++) {
    sum += nums[i]!;
    const r = k === 0 ? sum : ((sum % k) + k) % k;
    if (seen.has(r)) { if (i - seen.get(r)! >= 2) return true; }
    else seen.set(r, i);
  }
  return false;
}

Template connection

Map each remainder to its earliest index, and seed remainder 0 at index -1. A repeated remainder whose indexes differ by at least 2 is a subarray of length at least 2. A later copy of the same remainder does not replace the earliest index.

Reflection

  • You want a subarray sum that is a multiple of k, length at least 2. The same pref % k with an index gap of at least 2. Why store the remainder, not the raw prefix?
  • The map stores the earliest index of each remainder. What goes wrong with k = 0, and with Python’s signed %?
  • One element that is a multiple of k is not enough. The length is 1.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Subarray length ≥ 2 whose sum is a multiple of k=6.

23
0
2
1
4
2
6
3
7
4

need same prefix mod, gap ≥ 2

Key:CurrentActive rangeMatchSettled