Continuous Subarray Sum (LeetCode 523): Solution and Explanation

Medium
Array
Hash Table
Math
Prefix Sum

Given an array of non-negative integers and an integer k, decide whether some contiguous subarray of length at least two has a sum that is a multiple of k. Return true or false.

Intuition

Checking every subarray with a running sum takes O(n^2) time, which is too slow for 10^5 elements. Prefix sums turn each subarray sum into a difference: sum(nums[l..r]) = prefix[r] - prefix[l-1].

A difference is a multiple of k exactly when both prefix sums leave the same remainder when divided by k. So instead of remembering sums, remember remainders.

Walk the array once, keeping the running sum mod k. If the current remainder was already seen at some earlier prefix index j, then nums[j+1..i] sums to a multiple of k.

The length rule says that subarray must have at least two elements, so i - j must be at least 2. Storing only the earliest index for each remainder gives the longest possible subarray, which is the one most likely to pass that check. Seeding remainder 0 at index -1 handles subarrays that start at index 0.

Approach: Prefix remainders with earliest index

  1. Create a map first with {0: -1} and set total = 0.
  2. For each index i, update total = (total + nums[i]) % k.
  3. If total is in the map and i - first[total] >= 2, return true.
  4. If total is not in the map, store first[total] = i. If it is there but too close, leave the older index alone.
  5. After the loop, return false.

Step-by-step example

nums = [23,2,4,6,7], k = 6
  1. Start with first = {0: -1}.
  2. i = 0: total = 23 % 6 = 5, which is new, so store first[5] = 0.
  3. i = 1: total = (5 + 2) % 6 = 1, new, store first[1] = 1.
  4. i = 2: total = (1 + 4) % 6 = 5. Remainder 5 was stored at index 0, and 2 - 0 = 2, so nums[1..2] = [2,4] sums to 6. Return true.

Code: Python, Java, C++

1class Solution:
2    def checkSubarraySum(self, nums: List[int], k: int) -> bool:
3        first = {0: -1}
4        total = 0
5        for i, num in enumerate(nums):
6            total = (total + num) % k
7            if total in first:
8                if i - first[total] >= 2:
9                    return True
10            else:
11                first[total] = i
12        return False
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the array with constant-time hash map lookups and inserts.

Space

O(min(n, k))

The map holds at most one entry per distinct remainder, and there are at most k remainders and at most n + 1 prefixes.

Other approaches

All pairs with running sums (time O(n^2), space O(1))

Fix each start index and extend the end, adding one element at a time and checking the sum mod k once the length reaches two. Simple, but quadratic.

Delayed set of remainders (time O(n), space O(min(n, k)))

Keep a set of remainders, but add the remainder from index i - 1 only when processing index i. Any hit in the set is then automatically at least two elements back. Same complexity as the map version.

Common mistakes

  • Forgetting to seed remainder 0 at index -1. Without it, a prefix like [2,4] with k = 6 is missed because no earlier prefix has remainder 0.
  • Overwriting the stored index when a remainder repeats too early. That makes later subarrays look shorter than they are, for example [5,0,0,0] with k = 3.
  • Treating a single element as a valid subarray. A lone 0 is a multiple of k but has length one, so [0] must return false.
  • Checking sum % k == 0 only for whole prefixes. That ignores subarrays that start in the middle of the array.

Frequently asked questions

Why do equal remainders guarantee a multiple of k?

If prefix[i] = a * k + r and prefix[j] = b * k + r, their difference is (a - b) * k, which is a multiple of k. That difference is exactly the sum of nums[j+1..i].

Why store the earliest index instead of the latest?

The only extra condition is length at least two. The earliest index gives the longest subarray ending at the current position, so if any earlier match works, the earliest one does.

What about two consecutive zeros?

Two zeros sum to 0, which is a multiple of every k. The remainder stays the same across both, and the gap is two, so the algorithm returns true.