The 30 second answer
A subarray sum is a multiple of k exactly when two prefix sums have the same remainder mod k. So I store the first index where each remainder appeared, seeding remainder zero at index minus one. If I see a remainder again at least two positions later, the subarray in between has length two or more and a sum divisible by k.
Problem Return true if there is a contiguous subarray of length at least 2 whose sum is a multiple of k. Original: LeetCode 523: Continuous Subarray Sum.
Understanding the prompt "Multiple of k" includes 0. "At least two elements" is the trap.
Pattern recognition Prefix sum plus hash map, keyed on the remainder. Storing the first index lets you check the length.
Brute force Check every subarray of length 2 or more: O(n²).
Optimal firstIndex.put(0, -1). For each i, take rem = (rem + nums[i]) % k. If rem was seen at index j and i − j ≥ 2, return true. Otherwise record rem only if it is new, so the earliest index is kept.
Alternatives None simpler. Explain why you keep the first index rather than the latest.
Java solution
import java.util.HashMap;
public class ContinuousSubarraySum {
static boolean checkSubarraySum(int[] nums, int k) {
var firstIndex = new HashMap<Integer, Integer>(); // remainder -> earliest index
firstIndex.put(0, -1);
int rem = 0;
for (int i = 0; i < nums.length; i++) {
rem = (rem + nums[i]) % k;
var j = firstIndex.get(rem);
if (j == null) firstIndex.put(rem, i);
else if (i - j >= 2) return true;
}
return false;
}
public static void main(String[] args) {
System.out.println(checkSubarraySum(new int[] {23, 2, 4, 6, 7}, 6)); // true
System.out.println(checkSubarraySum(new int[] {23, 2, 6, 4, 7}, 13)); // false
System.out.println(checkSubarraySum(new int[] {0}, 1)); // false (length 1)
}
}Complexity O(n) time and O(min(n, k)) space.
Edge cases
- A single element.
- Zeros, as in [0,0], which is a valid length-2 subarray.
- Negative numbers, if a variant allows them: Java's
%can return a negative value, so normalise with((x % k) + k) % k.
Follow-ups
- Count such subarrays instead of returning a boolean (LeetCode 974 counts subarrays divisible by k).
- Return the longest one.
Tests [23,2,4,6,7] with k=6 returns true. [23,2,6,4,7] with k=13 returns false. [0] with k=1 returns false.
How to say it in the interview "Two equal prefix remainders mod k mean the elements between them sum to a multiple of k. I store the first index of each remainder, starting with remainder 0 at index −1, and return true when a repeat is at least two positions away."
Sources (2)
- LeetCode 523: Continuous Subarray Sumleetcode.com
- JLS 17, 15.17.3: Remainder operator %docs.oracle.com