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 7 test cases (4 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 →Let `S(j)` be the sum of the first `j` elements. A subarray ending at index `j` sums to `k` exactly when some earlier prefix `S(i)` equals `S(j) - k`. Scan once, maintaining a running sum and a hash map from prefix-sum value to its occurrence count (seeded with `{0: 1}` for subarrays starting at index 0). At each element, add `count[S - k]` to the answer, then record the current sum.
This handles negative numbers, which break sliding-window approaches.
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.