523. Continuous Subarray Sum
Problem
Decide whether nums has a contiguous subarray of length at least 2 whose sum is a multiple of k (0 counts as a multiple).
Example: nums = [23,2,4,6,7], k = 6 → true ([2,4] sums to 6)
Constraints: n ≤ 10⁵; values are non-negative; 1 ≤ k ≤ 2³¹ − 1.
A subarray sum is a multiple of k ⇔ two prefix sums have the same remainder mod k. Store the first index of each remainder (seed 0 → −1); a repeat at least 2 positions later wins.
Complexity: O(n).
class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
first = {0: -1}
pre = 0
for i, x in enumerate(nums):
pre = (pre + x) % k
if pre in first:
if i - first[pre] >= 2:
return True
else:
first[pre] = i
return False
assert Solution().checkSubarraySum([23, 2, 4, 6, 7], 6) is True
assert Solution().checkSubarraySum([23, 2, 6, 4, 7], 13) is False
assert Solution().checkSubarraySum([5, 0, 0, 0], 3) is True
class Solution {
public boolean checkSubarraySum(int[] nums, int k) {
Map<Integer, Integer> first = new HashMap<>();
first.put(0, -1);
int pre = 0;
for (int i = 0; i < nums.length; i++) {
pre = (pre + nums[i]) % k;
Integer j = first.putIfAbsent(pre, i);
if (j != null && i - j >= 2) return true;
}
return false;
}
}
func checkSubarraySum(nums []int, k int) bool {
first := map[int]int{0: -1} // prefix sum mod k -> first index
pre := 0
for i, x := range nums {
pre = (pre + x) % k
if j, ok := first[pre]; ok {
if i-j >= 2 {
return true
}
} else {
first[pre] = i
}
}
return false
}