Continuous Subarray Sum (LeetCode 523): Solution and Explanation
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
- Create a map
firstwith{0: -1}and settotal = 0. - For each index
i, updatetotal = (total + nums[i]) % k. - If
totalis in the map andi - first[total] >= 2, return true. - If
totalis not in the map, storefirst[total] = i. If it is there but too close, leave the older index alone. - After the loop, return false.
Step-by-step example
nums = [23,2,4,6,7], k = 6
- Start with
first = {0: -1}. i = 0: total = 23 % 6 = 5, which is new, so storefirst[5] = 0.i = 1: total = (5 + 2) % 6 = 1, new, storefirst[1] = 1.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 False1class Solution {
2 public boolean checkSubarraySum(int[] nums, int k) {
3 Map<Integer, Integer> first = new HashMap<>();
4 first.put(0, -1);
5 int total = 0;
6 for (int i = 0; i < nums.length; i++) {
7 total = (total + nums[i]) % k;
8 if (first.containsKey(total)) {
9 if (i - first.get(total) >= 2) {
10 return true;
11 }
12 } else {
13 first.put(total, i);
14 }
15 }
16 return false;
17 }
18}1class Solution {
2public:
3 bool checkSubarraySum(vector<int>& nums, int k) {
4 unordered_map<int, int> first;
5 first[0] = -1;
6 int total = 0;
7 for (int i = 0; i < (int)nums.size(); i++) {
8 total = (total + nums[i]) % k;
9 if (first.count(total)) {
10 if (i - first[total] >= 2) {
11 return true;
12 }
13 } else {
14 first[total] = i;
15 }
16 }
17 return false;
18 }
19};Time and space complexity
O(n)
One pass over the array with constant-time hash map lookups and inserts.
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 == 0only 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.