Prefix Sums & Difference Arrays for Constant-Time Range Queries
Prefix Sums & Difference Arrays for Constant-Time Range Queries
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$):
$$\text{Sum}(L, R) = \begin{cases} \text{prefix}[R] & \text{if } L = 0 \\ \text{prefix}[R] - \text{prefix}[L - 1] & \text{if } L > 0 \end{cases}$$
3. Difference Arrays: $O(1)$ Range Updates
Suppose you need to add $+V$ to all elements in range $[L, R]$ for 100,000 queries:
- Naive loop: $O(R - L) \approx O(n)$ per update.
- Difference Array Technique:
- 1$\text{diff}[L] \mathrel{+}= V$ (marks the start of the increment)
- 2$\text{diff}[R + 1] \mathrel{-}= V$ (cancels out the increment after the boundary!)
- 3After all $q$ queries, compute the prefix sum of the difference array in a single $O(n)$ pass!
4. Multi-Language Implementations: Prefix Sum Class
Python 3:
Modern JavaScript / TypeScript:
5. Trace Table: Range Updates via Difference Array
Initial Array of size 5: [0, 0, 0, 0, 0]
- Query 1: Add $+10$ to range $[1, 3]$
- Query 2: Add $+5$ to range $[2, 4]$
| Step | Index 0 | Index 1 | Index 2 | Index 3 | Index 4 | Index 5 |
|---|---|---|---|---|---|---|
| Initial diff | 0 | 0 | 0 | 0 | 0 | 0 |
After Q1: diff[1]+=10, diff[4]-=10 | 0 | +10 | 0 | 0 | -10 | 0 |
After Q2: diff[2]+=5, diff[5]-=5 | 0 | +10 | +5 | 0 | -10 | -5 |
| Prefix Sum Pass (Final Values) | 0 | 10 | 15 | 15 | 5 | 0 |
Resulting array [0, 10, 15, 15, 5] generated with zero looping per query!
Multiple Choice Questions
sumRange(L, R) using a precomputed prefix sum array?prefix[0] = 0?Singly Linked Lists: Node Architecture, Traversal & In-Place Reversal
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.