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 →Walk the array once carrying a running total. At each index, add the current element to the total and write the total out. That is the whole algorithm - and the array it produces is the tool the harder prefix-sum problems rely on, because the sum of any range `[i, j]` is `prefix[j] - prefix[i - 1]`, an O(1) lookup after O(n) setup.
The in-place variant (`nums[i] += nums[i - 1]`) uses no extra space, which matters when the caller does not need the original array.
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.