Running total
O(n) + O(1)Store prefix[i], the sum of everything before index i. A range sum is prefix[j + 1] - prefix[i].
Add things up once, from the left, and keep every running total. Then the sum of any stretch is one subtraction instead of a loop.
Store prefix[i], the sum of everything before index i. A range sum is prefix[j + 1] - prefix[i].
Walk once, keeping the running total. A run ending here sums to k exactly when total - k was an earlier total, so count those in a map.
Sweep once from the left and once from the right. Each position then knows everything on either side of it.
Reach for it when the answer at i depends on all the other elements, such as a balance point or a product without division.Go deeper: Prefix sums: any range total in one subtractionRun it backwards. Mark +v where a range starts and −v just after it ends, then one running sum rebuilds every value.
Reach for it when many updates add to whole ranges and you only read the result at the end.Go deeper: Prefix sums: any range total in one subtractionRunning totals of positive numbers only go up, so they are sorted. Binary search them to find where a value lands.
Reach for it when you need to pick by weight, or find the first point a running total passes a target.Go deeper: Where log n comes fromThe one that surprises people. Keep a running total and a map of totals seen so far, and counting subarrays that sum to k takes a single pass.
| # | Problem | Pattern | Difficulty | Solution |
|---|---|---|---|---|
| 1 | Find the Highest Altitude | Running total | Easy | Read |
| 2 | Find Pivot Index | Prefix and suffix | Easy | Read |
| 3 | Product of Array Except Self | Prefix and suffix | Medium | Read |
| 4 | Subarray Sum Equals K | Prefix + hash map | Medium | Read |
| 5 | Contiguous Array | Prefix + hash map | Medium | Read |
| 6 | Continuous Subarray Sum | Prefix + hash map | Medium | Read |
| 7 | Car Pooling | Difference array | Medium | Read |
| 8 | Random Pick with Weight | Prefix + binary search | Medium | Read |
| 9 | Path Sum III | Prefix + hash map | Medium | Read |
| 10 | Count of Range Sum | Running total + merge sort | Hard | Read |