Detect a Run of Two or More Elements Summing to a Multiple of k
Arrays & HashingAuto-graded · 23 test casesLast updated
Tests prefix-sum reasoning with hashing: detecting a contiguous run of length at least two whose sum is divisible by k, including the k = 0 special case.
Problem
You are given an integer array nums and an integer k. Decide whether there is a contiguous block of elements whose length is at least 2 and whose sum is a multiple of k.
Return True if such a block exists, otherwise return False.
Definitions:
- A block is a run of consecutive positions
nums[l..r]withr - l + 1 >= 2. - A sum is a multiple of
kwhen it equalsk * mfor some integerm. This is the same as being a multiple of|k|. - If
k = 0, the requirement changes: the block's sum must be exactly0.
Explain your approach, and state the time and space complexity of your solution.
Constraints
0 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9-10^9 <= k <= 10^9- Blocks must have length at least 2. A single element never counts, even if it is itself a multiple of
k. - Return a Python
bool.
Examples
Example 1
Input: has_divisible_run([23, 2, 4, 6, 7], 6)
Output: True
Example 2
Input: has_divisible_run([23, 2, 6, 4, 7], 6)
Output: True
Example 3
Input: has_divisible_run([23, 2, 6, 4, 7], 0)
Output: False
Hints
Hint 1
Turn the block sum into a difference of two prefix sums. If P[i] is the sum of the first i+1 elements, the block from index j+1 to i has sum P[i] - P[j], which is a multiple of k exactly when P[i] and P[j] share a remainder mod |k|.
Hint 2
Store only the earliest index for each remainder. For the length-at-least-2 rule, the earliest index gives the longest possible block, so it is the only one worth remembering. Seed the map with remainder 0 at index -1 so that blocks starting at index 0 are counted.
Hint 3
When k = 0, skip the remainder step and use the raw prefix sum as the key. Also check whether abs(k) works as the divisor for negative k, and how your language's % handles negative prefix sums.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use prefix sums. Let P[i] be the sum of the first i + 1 elements, and let P[-1] = 0. The block nums[j+1..i] has sum P[i] - P[j]. That difference is a multiple of |k| exactly when P[i] and P[j] have the same remainder mod |k|. So the question becomes: are there two prefix positions at least 2 apart with the same key?
Scan left to right and keep a hash map from each key to the earliest index where it appeared.
- Start with
{0: -1}. This represents the empty prefix and lets blocks that begin at index 0 be found. - At index
i, compute the key. Ifk = 0, the key is the raw prefix sum. Otherwise it isprefix % |k|. - If the key is already stored at index
jandi - j >= 2, returnTrue. - If the key is new, store
i. - If the key is stored but
i - j == 1, leave the map unchanged.
Why It Is Correct
Storing the earliest index is enough. For a fixed i, the best earlier partner is the smallest index j with the same key, because it yields the longest block. If that one is too close, no later index with that key can help. Since the map keeps only the earliest index, the lookup is exact for the length rule.
Not overwriting on a distance-1 match is required. A distance-1 match means that one element by itself has the right key. A future index may need the older, farther-back index, so overwriting would lose a valid candidate.
The sentinel {0: -1} is required. It represents the empty prefix. Without it, a block starting at index 0 would never be detected.
Negative values and k. A multiple of k is the same as a multiple of |k|, so the code uses abs(k). In Python, % with a positive modulus always returns a value in [0, |k|), even when the prefix is negative, so equal keys really mean the prefixes are congruent. In languages where % can be negative, normalize with ((p % d) + d) % d.
Completeness. If a valid block nums[j+1..i] exists, then P[j] and P[i] share a key. When the scan reaches i, the map holds an index <= j for that key, so the distance is at least i - j >= 2, and the function returns True no later than i.
Soundness. The function returns True only when two prefixes with equal keys are at least 2 apart, and that is exactly a valid block.
Complexity
- Time: O(n). The array is scanned once, and each map operation takes expected O(1) time.
- Space: O(min(n, |k|)) when
k != 0, because there are at most|k|distinct remainders. Whenk = 0, the keys are raw prefix sums, so the space is O(n).
Edge Cases
- Empty or single-element input returns
False. [0, 0]returnsTruefor anyk, because the sum is 0.k = 1(or-1) returnsTruewhenevern >= 2.[6]withk = 6returnsFalse, because a single element does not count.[23, 2, 4]withk = -6returnsTrue, because[2, 4]sums to 6.
Solution
from typing import List
def has_divisible_run(nums: List[int], k: int) -> bool:
earliest = {0: -1} # remainder (or raw prefix when k == 0) -> earliest index
running = 0
divisor = abs(k)
for i, x in enumerate(nums):
running += x
key = running if divisor == 0 else running % divisor
if key in earliest:
if i - earliest[key] >= 2:
return True
else:
earliest[key] = i
return False