Spend O(n) once to build cumulative info, then answer each range query in O(1). Same trick powers subarray counting, submatrix sums, and bulk range updates.
Prefix sum array
- Make it one longer than the list with a leading
0:prefix[i]= sum of the firstielements (indexes0..i-1). - Build:
prefix[0] = 0,prefix[i+1] = prefix[i] + nums[i]. - Range sum of
[l, r]inclusive =prefix[r+1] - prefix[l]inO(1). The leading0removes thel == 0special case. nums=[3,1,4,1,5,9]->prefix=[0,3,4,8,9,14,23];range_sum(1,3) = prefix[4] - prefix[1] = 6.
Subarray sum equals k (prefix + hash map)
- Subarray
i..jsums tokiffprefix[i] = running - k. Count earlier prefixes equal torunning - k. - Seed the map with
{0: 1}(the empty prefix) so subarrays starting at index0are counted. - One
O(n)pass,O(n)space; handles negatives and overlaps (a sliding window cannot).
def subarray_sum_count(nums: list[int], k: int) -> int:
counts, running, total = {0: 1}, 0, 0
for x in nums:
running += x
total += counts.get(running - k, 0)
counts[running] = counts.get(running, 0) + 1
return total # [1,2,3], k=3 -> 2 ; [1,1,1], k=2 -> 2
2-D prefix sum (submatrix)
- Padded table:
P[i+1][j+1] = grid[i][j] + P[i][j+1] + P[i+1][j] - P[i][j](inclusion-exclusion). - Query
(r1,c1)..(r2,c2)=P[r2+1][c2+1] - P[r1][c2+1] - P[r2+1][c1] + P[r1][c1]. - Build
O(rows·cols), each queryO(1).
Difference array (bulk range-add)
- Add
valover[l, r]:diff[l] += val,diff[r+1] -= val(eachO(1)). Realize with one prefix pass:running += diff[i]. Sizediffasn+1sor+1is valid. - Go-to for “+1 over every interval” (overlap counts):
+1at each start,-1past each end. n=5,[(1,3,2),(2,4,3),(0,2,-1)]->[-1, 1, 4, 5, 3].
Kadane’s max subarray (related running-value idea)
- Largest contiguous sum in
O(n)time,O(1)space:current = max(x, current + x), trackbest. - Init both to
nums[0], not0, or an all-negative list wrongly returns0.
Pitfalls
- Range formula is
prefix[r+1] - prefix[l];prefix[l-1]breaks atl=0(Python-1wraps). - Prefix array length
n+1with leading0; diff array lengthn+1for ther+1write. - Seed subarray-sum map with
{0: 1}, not{}.
Summary table
| technique | precompute | per query/update | space |
|---|---|---|---|
| prefix range sum | O(n) | O(1) | O(n) |
| subarray sum = k | — | O(n) total | O(n) |
| 2-D prefix sum | O(rows·cols) | O(1) | O(rows·cols) |
| difference array | O(1)/update | O(n) realize | O(n) |
| Kadane’s | — | O(n) total | O(1) |