Continuous Subarray Sum

Does any subarray of length >= 2 sum to a multiple of k? Prefix sums modulo k.

Medium
Time O(N) Space O(N)
LeetCode
3 min read
hash-map prefix-sum modular

Problem#

Given an integer array nums and integer k, return true if there exists a contiguous subarray of length at least 2 whose sum is a multiple of k.

Examples#

  • nums = [23,2,4,6,7], k = 6true ([2,4]).
  • nums = [23,2,6,4,7], k = 6true ([23,2,6,4,7] sums to 42).
  • nums = [1,2,3], k = 5false.

Constraints#

  • 1 <= nums.length <= 10^5, 0 <= nums[i] <= 10^9, 1 <= k <= 2^31 - 1.

Hints#

Hint
If two prefix sums share the same residue mod k, the subarray between them sums to a multiple of k.

Approach#

Compute running prefix-sum mod k. Store firstIndex[residue] (init firstIndex[0] = -1 so a prefix that itself is a multiple of k counts). When we see a residue again with i - firstIndex >= 2, we have our subarray.

Solution#

Continuous Subarray Sum
class Solution {
public:
bool checkSubarraySum(vector<int>& nums, int k) {
unordered_map<int,int> firstIdx;
firstIdx[0] = -1;
int prefix = 0;
for (int i = 0; i < (int)nums.size(); ++i) {
prefix = (prefix + nums[i]) % k;
auto it = firstIdx.find(prefix);
if (it != firstIdx.end()) {
if (i - it->second >= 2) return true;
} else {
firstIdx[prefix] = i;
}
}
return false;
}
};

Editorial#

Two prefix sums P[i] and P[j] share the same residue mod k iff (P[j] - P[i]) % k == 0 — and that difference is the sum of nums[i+1..j]. Keeping the first occurrence maximizes the window length, helping the >= 2 check. Initializing firstIdx[0] = -1 correctly handles the case where the prefix from index 0 is itself a multiple of k.

Complexity#

  • Time: O(N).
  • Space: O(N).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.