ReviseAlgo Logo
EasyHigh Frequency20 min

Prefix Sum

Answer range sum queries in O(1) after O(n) preprocessing using cumulative sums.

Precompute cumulative sums in O(n). Then answer any range-sum query in O(1): rangeSum(l,r) = prefix[r+1] - prefix[l].

Prefix Sum

Operations — Step by Step

Build Prefix Array

O(n)prefix[0]=0 sentinel handles subarrays from index 0
Step-by-step1 / 6
marker
0
0
marker
1
1
marker
3
2
marker
6
3
marker
10
4
marker
15
5

prefix[0] = 0

Sentinel. Sum of zero elements = 0.