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
UnverifiedIdea. 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).
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
Prefix sums modulo k; a repeated remainder means a subarray sum divisible by k (length ≥ 2).
Reflection
- You want a subarray sum that is a multiple of
k, length at least 2. The samepref % kwith 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
kis not enough. The length is 1.