Contiguous Subarray with Sum Divisible by K
Arrays & HashingAuto-graded · 21 test casesLast updated
Tests whether a candidate can apply prefix-sum modular arithmetic to detect a length-≥2 subarray whose sum divides evenly by k in linear time.
Contiguous Subarray with Sum Divisible by K
You are given an array of non-negative integers nums and a positive integer k.
Return True if there is a contiguous subarray of length at least 2 whose elements sum to a multiple of k. Otherwise return False.
A sum is a multiple of k when the remainder after dividing by k equals zero.
Constraints
1 <= len(nums) <= 100 0000 <= nums[i] <= 1 000 000 0001 <= k <= 1 000 000 000- Aim for an
O(n)solution.
Examples
Example 1
Input: check_subarray_sum([23, 2, 4, 6, 7], 6)
Output: True
Example 2
Input: check_subarray_sum([23, 2, 6, 4, 7], 6)
Output: True
Example 3
Input: check_subarray_sum([23, 2, 6, 4, 7], 13)
Output: False
Hints
Hint 1
Define the prefix sum P[i] as the sum of the first i elements. The sum of subarray nums[a..b] equals P[b+1] − P[a]. What condition on P[b+1] and P[a] guarantees that sum is divisible by k?
Hint 2
Two prefix sums that share the same remainder mod k correspond to a subarray whose sum is divisible by k. Use a dictionary to record the earliest index where each remainder was seen, then check whether the gap between that index and the current index is at least 2.
Hint 3
Seed your remainder map with {0: −1} before you start. This handles subarrays that begin at index 0. Never overwrite an existing entry — you always want the earliest occurrence so the gap can only grow, never shrink.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core Observation
Define the prefix sum P[i] as the sum of the first i elements (P[0] = 0). The sum of the subarray nums[a..b] (inclusive, 0-indexed) is P[b+1] − P[a]. That difference is divisible by k exactly when P[b+1] and P[a] leave the same remainder when divided by k.
So the problem reduces to: find two prefix-sum indices j < i such that P[i] ≡ P[j] (mod k) and i − j >= 2 (guaranteeing a subarray of length at least 2).
Algorithm
Scan nums once, maintaining a running prefix sum modulo k. Keep a dictionary first_index mapping each remainder to the smallest index where it was first seen.
Before the loop, seed the map with {0: −1}. This represents the empty prefix P[0] = 0, with the virtual position −1, so any subarray starting at index 0 is handled correctly.
At each index i:
- Update
prefix = (prefix + nums[i]) % k. - If
prefixis already in the map andi − first_index[prefix] >= 2, returnTrue. - If
prefixis not in the map, recordfirst_index[prefix] = i. - Critically, do not overwrite an existing entry. Keeping the earliest index maximises every future gap, so no valid pair is ever missed.
If the loop finishes without finding a match, return False.
Why It Is Correct
- Earliest index only. If
jis the first index with remainderrand some later indexialso has remainderr, the gapi − jis at least as large as any gap we would get from a later occurrence ofr. Overwriting would risk losing a valid pair. - The
{0: −1}seed lets the algorithm detect subarrays that begin at position 0 without special-casing them. For example, withnums = [2, 4]andk = 6, the running sum reaches remainder 0 ati = 1, and1 − (−1) = 2, so the whole array qualifies. - Length-1 guard. A gap of exactly 1 would mean a single element divisible by
k. The>= 2check correctly excludes those.
Worked Trace
nums = [23, 2, 4, 6, 7], k = 6, seeded with {0: −1}:
| i | nums[i] | running prefix mod 6 | first_index | action |
|---|---|---|---|---|
| 0 | 23 | 5 | — | record 5 → 0 |
| 1 | 2 | 1 | — | record 1 → 1 |
| 2 | 4 | 5 | 5 → 0 | gap = 2 − 0 = 2 ≥ 2 → True |
The matching subarray is nums[1..2] = [2, 4] with sum 6.
Edge Cases
len(nums) == 1: the loop runs once but can never find a gap of 2, soFalseis returned correctly.k = 1: every integer is divisible by 1, so every prefix remainder is 0. The seeded{0: −1}triggers aTruereturn as soon asi = 1, which is correct wheneverlen(nums) >= 2.- Consecutive zeros such as
[0, 0]: sum is 0, divisible by anyk. The remainder stays 0 ati = 1, the seeded entry gives a gap of 2, andTrueis returned.
Complexity
- Time:
O(n)— one pass through the array with O(1) dictionary operations per step. - Space:
O(min(n, k))— at mostkdistinct remainders can be stored, and at mostnentries are ever inserted.
from typing import List
def check_subarray_sum(nums: List[int], k: int) -> bool:
# Maps each prefix-sum remainder to the earliest index at which it appeared.
# The virtual index -1 represents the empty prefix (sum = 0) before index 0.
first_index = {0: -1}
prefix = 0
for i, value in enumerate(nums):
prefix = (prefix + value) % k
if prefix in first_index:
# A gap of >= 2 means the subarray between the two positions
# has length >= 2.
if i - first_index[prefix] >= 2:
return True
else:
# Only record the first occurrence so the gap can never shrink.
first_index[prefix] = i
return False