SDE & MLE Prep

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