When dealing with frequent range sum queries or bulk range updates on an array, naive solutions require $O(n)$ per query, resulting in an unscalable $O(n \times q)$ for $q$ queries. Prefix Sum Arrays solve range sum queries in $O(1)$ constant time, while Difference Arrays apply range updates across intervals in $O(1)$ constant time.
1. Real-World Analogy: The Odometer & Ledger
Imagine tracking your car's fuel expenses:
Instead of writing down how much you spent on every 5 km interval and adding them up every time someone asks your expenses between day 10 and day 20, you record your running cumulative total at the end of every day.
To find spending between Day $L$ and Day $R$, you simply compute:
$$\text{Total}(L \to R) = \text{Odometer}(R) - \text{Odometer}(L - 1)$$ A single subtraction gives you the exact total instantly!
2. Prefix Sum Array Construction & Formula
Given an array arr: $$\text{prefix}[0] = \text{arr}[0]$$ $$\text{prefix}[i] = \text{prefix}[i - 1] + \text{arr}[i]$$
Range Sum Query Formula (Inclusive indices $L$ to $R$):