sagelearnai

Prefix Sums

Signal: many range-sum queries, "subarray sum equals k", "balance point", counting subarrays with a property, or products of everything except one element.

Core idea: precompute P[i] = a[0] + … + a[i−1] (with P[0] = 0). Then the sum of any range a[l..r] is P[r+1] − P[l] in O(1).

a 31415 P 0348914 sum(a[1..3]) = 1 + 4 + 1 = 6 = P[4] − P[1] = 9 − 3 = 6 One O(n) pass to build P; every range query afterwards is a single subtraction.

Prefix sum + hash map

The powerful variant: "count subarrays whose sum is k". A subarray (l, r] sums to k exactly when P[r] − P[l] = k, i.e., P[l] = P[r] − k. Scan once, keeping a map prefix value → how many times seen:

python
from collections import defaultdict
count = defaultdict(int); count[0] = 1     # the empty prefix
p = ans = 0
for x in nums:
    p += x
    ans += count[p - k]                    # earlier prefixes that complete a k-sum here
    count[p] += 1

This works with negative numbers, where sliding windows fail. The same idea generalizes: "equal number of 0s and 1s" (map 0 → −1, then look for sum 0), "sum divisible by k" (store p mod k).

Problems

  1. Find Pivot Index (Easy): left sum == total − left − nums[i]
  2. Range Sum Query - Immutable (Easy): Precompute prefix sums; answer = P[r+1] − P[l]
  3. Product of Array Except Self (Medium): Prefix products × suffix products, no division
  4. Subarray Sum Equals K (Medium): Count earlier prefixes equal to current − k
  5. Contiguous Array (Medium): Map 0→−1; longest subarray with prefix sum repeated
  6. Subarray Sums Divisible by K (Medium): Count pairs of equal prefix remainders (normalized mod k)
  7. Continuous Subarray Sum (Medium): Equal prefix remainders mod k, at least 2 apart
  8. Range Sum Query 2D - Immutable (Medium): 2-D prefix sums with inclusion–exclusion
  9. Running Sum of 1d Array (Easy): out[i] = out[i−1] + nums[i]
  10. Find the Highest Altitude (Easy): Max over prefix sums, starting at 0
  11. Minimum Value to Get Positive Step by Step Sum (Easy): startValue = 1 − min prefix sum (at least 1)
  12. Corporate Flight Bookings (Medium): Difference array: +seats at first, −seats after last, then prefix sum
  13. Number of Ways to Split Array (Medium): Compare prefix sum with total − prefix at each split