See the idea in motion
Change an input. Follow the state. Build your intuition.
Session 06
Prefix sum explorer
Answer a range sum with two lookups.
Prefix sum explorer
Query [l, r] is zero-based and inclusive. P[k] stores the total of the first k values; P[0] is zero.
Input array a
30
11
42
13
54
95
Prefix array P
00
31
42
83
94
145
236
P[5] − P[1] = 14 − (3) = 11
Preprocess once in O(n). Each range sum then takes O(1).
Guided simulation · Change the inputs to test your understanding.