Prefix Sum & Difference Arrays
The Mental Model
Imagine you’re a cashier and need to tell customers their subtotal at any point during shopping. Instead of adding items from scratch each time, you keep a running total. That’s prefix sum—precompute cumulative sums so range queries become O(1).Pattern Recognition Signal: Whenever you see “sum of elements from index L to R” or “multiple range queries on static array”, think Prefix Sum.
When to Use Prefix Sum
Use When
- Multiple range sum queries
- Array is static (no updates)
- Need O(1) per query after O(n) preprocessing
- Subarray sum equals target problems
Don't Use When
- Array has frequent updates (use Segment Tree)
- Only one query (just iterate)
- Need min/max in range (use Sparse Table or Segment Tree)
The Core Idea
Building Prefix Sum Array
sum(L, R) = prefix[R+1] - prefix[L]
Why? Because prefix[R+1] contains sum of elements 0 to R, and prefix[L] contains sum of elements 0 to L-1. Subtracting gives us exactly L to R.
Implementation Template
Pattern 1: Subarray Sum Equals K
Problem: Count subarrays with sum equal to K. Identification Signals:- “Count subarrays” or “find subarray”
- “Sum equals K”
- Constraints allow O(n) solution
prefix[j] - prefix[i] = K, then subarray (i, j] has sum K. Rearranging: prefix[i] = prefix[j] - K. Use a hashmap to count prefix sums seen so far.
Pattern 2: 2D Prefix Sum
Problem: Answer multiple rectangle sum queries on a 2D grid. The Insight: Build a 2D prefix sum whereprefix[i][j] = sum of all elements in the rectangle from (0,0) to (i-1, j-1).
Pattern 3: Difference Array (Range Updates)
Problem: Apply multiple range updates, then query final array. Identification Signals:- “Add value to range [L, R]” multiple times
- Query final values after all updates
- No queries between updates
Common Mistakes
Practice Problems (CP-31 & Codeforces)
Beginner (800-1100)
Intermediate (1100-1400)
Advanced (1400-1700)
Key Takeaways
The Formula
sum(L, R) = prefix[R+1] - prefix[L]Use Hashmap
For “subarray sum = K”, track prefix counts.
Difference Array
For multiple range updates, apply at endpoints.
Watch Overflow
Always use
long long for prefix sums.Next Up
Chapter 5: Two Pointers & Sliding Window
Master the art of solving subarray problems in linear time with elegant pointer techniques.