Arrays and strings · Intermediate

Prefix sums

Precompute running totals once so any range sum is one subtraction, and combine them with a hash map to count ranges that hit a target.

On this page
  1. The idea
  2. How to recognise it
  3. When not to use it
  4. Template
  5. Complexity
  6. Worked examples
  7. Pitfalls
  8. Practise it
  9. Learn the foundations
  10. References

The idea

Let P[i] be the sum of the first i elements, with P[0] = 0. Then the sum of a[l..r) is P[r] − P[l]. One O(n) pass turns every later range query into O(1).

The same subtraction turns "is there a range summing to k?" into "have I seen a prefix equal to P[r] − k?", which a hash map answers in expected O(1). That version works with negative numbers, where a sliding window does not.

The idea generalises to any operation with an inverse (sums, XOR, counts) and to products via a left pass and a right pass. Difference arrays are the reverse trick: record +v at l and −v at r so many range updates cost O(1) each and one prefix pass applies them all.

How to recognise it

  • Many range-sum (or range-count) queries over an array that does not change between queries.
  • You need "the number of subarrays whose sum is k", possibly with negative values.
  • A balance point: the sum on the left equals the sum on the right.
  • Many range increments followed by one read of the final array (difference array).

When not to use it

  • The array changes between queries: each update would rebuild O(n) prefixes. A Fenwick tree or segment tree handles that.
  • The operation has no inverse (min, max): P[r] − P[l] means nothing for them. Use a sparse table or a monotonic structure.

Template

Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.

# Build: P has n + 1 entries
P = [0] * (n + 1)
for i in range(n):
    P[i + 1] = P[i] + a[i]
range_sum(l, r) = P[r] - P[l]      # half-open [l, r)

# Count subarrays with sum k (works with negatives)
seen = map with {0: 1}
running = 0; count = 0
for x in a:
    running += x
    count += seen.get(running - k, 0)
    seen[running] += 1
return count
  • Seeding the map with {0: 1} counts subarrays that start at index 0.
  • Look up before you insert the current prefix, or a zero-length range gets counted when k = 0.

Complexity

Time O(n) build, O(1) per query, extra space O(n). The hash-map variant is expected O(n): hash lookups are expected O(1), with the usual worst case if many keys collide.

Worked examples

Range sums of [3, −1, 4, 2]

P = [0, 3, 2, 6, 8]. The sum of indices 1..3 (half-open [1, 4)) is P[4] − P[1] = 8 − 3 = 5, which matches −1 + 4 + 2.

Pitfalls

  • Off-by-one between inclusive and half-open ranges; pick half-open and keep P one longer than a.
  • Integer overflow on long arrays of large values; use a 64-bit accumulator.
  • Inserting the current prefix before the lookup.

Practise it

Solved problems with hints, a correctness argument and four tested implementations:

Learn the foundations

Related patterns

References

dsa.pattern.prefix-sums · version 1