Master cumulative sum techniques to optimize array operations.
0 / 5 topics completed
01
Introduction to Prefix Sum
The Prefix Sum is a powerful algorithmic pattern used to perform fast range queries on an array. By precomputing cumulative sums, we can answer queries about the sum of elements in any continuous subarray in O(1) time instead of O(N).
What is a Prefix Sum Array?
Given an array A of size N, its prefix sum array P is also of size N (or N+1 for convenience). Each element at index i in the prefix sum array stores the sum of all elements in the original array from index 0 to i.
P[i] = A[0] + A[1] + ... + A[i]
Index
0
1
2
3
4
Original Array (A)
2
4
6
8
10
Prefix Sum (P)
2
6
12
20
30
Practice: Introduction
If the original array is [1, 3, 5, 7], what is the prefix sum array?
Often, it's convenient to make the prefix sum array size N+1 and set P[0] = 0. This avoids out-of-bounds errors when querying sums that start from index 0.
03
Range Query Examples
Once the prefix sum array is built, finding the sum of elements between any two indices L and R (inclusive) is a simple subtraction operation.
Given P = [1, 4, 9, 16], what is the sum of elements from index 1 to 2 inclusive?
Answer: 8
Explanation: Sum from L=1 to R=2 is P[2] - P[0] = 9 - 1 = 8. (The original array is [1, 3, 5, 7], and A[1]+A[2] = 3+5 = 8).
04
Applications
Prefix sums are foundational and appear in numerous optimization problems.
1. Equilibrium Index
An equilibrium index is an index where the sum of elements to its left equals the sum to its right. We can find this efficiently using prefix sums.
2. Difference Arrays
If you need to perform many range additions (e.g., "Add 5 to all elements from L to R"), a difference array is the inverse of a prefix sum array and can perform this update in O(1) time.
3. 2D Prefix Sums
For a 2D matrix, a 2D prefix sum array allows finding the sum of elements within any rectangular sub-grid in O(1) time. The formula becomes: S = P[r2][c2] - P[r1-1][c2] - P[r2][c1-1] + P[r1-1][c1-1]
05
Practice Exercises
Test your understanding of the prefix sum technique.
Exercise 1: Finding Equilibrium
Given the array [-7, 1, 5, 2, -4, 3, 0], what is the equilibrium index? (Use the prefix sum approach).
Answer: Index 3
Explanation: At index 3 (value is 2), the sum of elements to the left is -7 + 1 + 5 = -1. The sum to the right is -4 + 3 + 0 = -1. Since both sides equal -1, index 3 is an equilibrium index.
Exercise 2: Time Complexity
If you have an array of N elements and need to answer Q range queries, what is the time complexity of using the prefix sum method versus calculating the sum directly each time?
Answer: O(N + Q) vs O(Q * N)
Explanation: Prefix sum takes O(N) to build and O(1) per query, leading to O(N + Q). Direct calculation takes O(N) per query, leading to O(Q * N).