Prefix Sum Pattern
The Prefix Sum pattern involves preprocessing an array to create a new array where each element at index i represents the sum of all elements from the start of the array up to index i. This technique allows for efficient sum queries on subarrays in constant time.
When to Use This Pattern
- When you need to perform multiple sum queries on subarrays
- When you need to calculate cumulative sums efficiently
- When dealing with range sum queries
- When optimizing problems that require repeated subarray sum calculations
Key Concepts
The fundamental idea is to precompute a prefix sum array P where:
\[ P[i] = \sum_{j=0}^{i} A[j] = A[0] + A[1] + \ldots + A[i] \]
Once we have this prefix array, we can calculate the sum of any subarray from index i to j in constant time using:
\[ \text{Sum}(i, j) = P[j] - P[i-1] \]
For the special case when i = 0, the sum is simply P[j].
Visual Representation
Prefix Sum Array Visualization
Query Example: Sum from index 1 to 3 = P[3] - P[0] = 10 - 1 = 9
This represents: A[1] + A[2] + A[3] = 2 + 3 + 4 = 9
Step-by-Step Simulation
Let's trace through building a prefix sum array with A = [1, 2, 3, 4, 5]:
Initial Array A: [1, 2, 3, 4, 5]
Step 0: P[0] = A[0] = 1
P = [1, _, _, _, _]
Step 1: P[1] = P[0] + A[1] = 1 + 2 = 3
P = [1, 3, _, _, _]
Step 2: P[2] = P[1] + A[2] = 3 + 3 = 6
P = [1, 3, 6, _, _]
Step 3: P[3] = P[2] + A[3] = 6 + 4 = 10
P = [1, 3, 6, 10, _]
Step 4: P[4] = P[3] + A[4] = 10 + 5 = 15
P = [1, 3, 6, 10, 15]
Final Prefix Array: [1, 3, 6, 10, 15]
Query Simulation
Now let's query the sum from index 1 to 3:
Query: Sum from index 1 to 3 (inclusive)
Direct calculation: A[1] + A[2] + A[3] = 2 + 3 + 4 = 9
Using prefix sum: P[3] - P[0] = 10 - 1 = 9
Why this works:
P[3] = A[0] + A[1] + A[2] + A[3] = 1 + 2 + 3 + 4 = 10
P[0] = A[0] = 1
P[3] - P[0] = (A[0] + A[1] + A[2] + A[3]) - A[0] = A[1] + A[2] + A[3] = 9