Skip to content
TOPIC · 10 PROBLEMS · 5 PATTERNS

Prefix sums

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.

How to spot a prefix sum problem

“subarray sum”Anything about the total of a contiguous run. The sum from i to j is the total up to j minus the total before i.
“equals k”Count or find the runs that hit an exact target. Negative numbers rule out a sliding window, so pair the totals with a hash map.
“many queries”Lots of range questions over data that does not change. Pay O(n) once and answer each one in O(1).

Five patterns cover almost everything

Prefix and suffix

O(n)

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 subtraction

Difference array

O(n + q)

Run 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 subtraction

Prefix + binary search

O(log n) per query

Running 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 from

The one template to memorise

The 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.

solution.py
def count_subarrays(nums, k):
seen = {0: 1} # prefix sum -> how many times it has appeared
total = count = 0
for x in nums:
total += x
count += seen.get(total - k, 0)
seen[total] = seen.get(total, 0) + 1
return count

Problems, easy to hard

Do them in order the first time
#ProblemPatternDifficultySolution
1Find the Highest AltitudeRunning totalEasyRead
2Find Pivot IndexPrefix and suffixEasyRead
3Product of Array Except SelfPrefix and suffixMediumRead
4Subarray Sum Equals KPrefix + hash mapMediumRead
5Contiguous ArrayPrefix + hash mapMediumRead
6Continuous Subarray SumPrefix + hash mapMediumRead
7Car PoolingDifference arrayMediumRead
8Random Pick with WeightPrefix + binary searchMediumRead
9Path Sum IIIPrefix + hash mapMediumRead
10Count of Range SumRunning total + merge sortHardRead
Next upStacksHeaps