Ever wondered how apps and games show instant totals—like scores, analytics, or stats without lag?
Behind that speed often hides a humble hero: Prefix Sum.
Imagine this:
You’ve got an array of numbers and multiple queries like:
“What’s the sum of values between index L and R?”
Looping through each query works… until you need to do it thousands of times. That’s when performance tanks.
The Real Trick
Prefix Sum precomputes totals so you don’t repeat work.
Example:
If arr = [2, 5, 1, 3], then prefix = [2, 7, 8, 11].
Want the sum from L to R?
Sum(L, R) = prefix[R] - prefix[L-1]
(Or just prefix[R] if L = 0).
No loops. Instant results.
Pseudo Code
# Build prefix sum
prefix[0] = arr[0]
for i from 1 to n-1:
prefix[i] = prefix[i-1] + arr[i]
# Answer queries fast
for each (L, R):
if L == 0:
result = prefix[R]
else:
result = prefix[R] - prefix[L-1]
Real World Impact
Finance & Analytics : Quick running totals & range calculations
Games : Instant score or health bar updates
Data Dashboards : Fast aggregations over large datasets
Naive way → O(N) per query
Prefix Sum → O(1) per query
It’s a tiny trick with big real-world impact.
For a full explanation with code, visuals, and edge cases, check out my Medium:
Mastering Prefix Sum — The Foundation of Fast Queries