We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
An easy 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 →Build `prefix` of length `n + 1` where `prefix[i]` is the sum of the first `i` elements, so `prefix[0] = 0`. Then:
```
sum(left..right) = prefix[right + 1] - prefix[left]
```
Preprocessing is O(n) once; every query is then two array reads and a subtraction.
The padded slot is the detail worth internalizing. Without it you would write `prefix[right] - (left > 0 ? prefix[left - 1] : 0)` - correct, but the branch is exactly the kind of edge case that gets fumbled under interview pressure. Padding makes the empty prefix a real value instead of a special case.
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.