We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A medium prefix sum problem, graded against 6 test cases (3 of them hidden).
Precomputed cumulative totals so any range query becomes one subtraction.
Reach for it when you see: Repeated range-sum queries, or counting subarrays that sum to a target.
More Prefix Sumproblems →The sum of the subarray `(i, j]` is `prefix[j] - prefix[i]`. That difference is divisible by `k` precisely when the two prefixes are congruent mod `k`. So the problem reduces to: how many pairs of prefix sums share a remainder?
Sweep once, maintaining a running remainder and a count of how many times each remainder has been seen. At each step, every earlier prefix with the same remainder forms a valid subarray ending here, so add that count before recording the current one. Seed the counter with remainder `0` at count `1` to represent the empty prefix - that is what lets subarrays starting at index 0 be counted.
The negative-number trap. In JavaScript (and C, Java, Go), `%` takes the sign of the dividend: `-3 % 5` is `-3`, so `-3` and `2` land in different buckets even though they are the same residue class, and the count comes out low. Normalizing with `((x % k) + k) % k` fixes it. Python's `%` is already floor-based and returns a non-negative result when `k > 0`, which is why the same algorithm ported from Python to JavaScript silently breaks.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.