What if you could answer any sum question instantly without adding numbers again and again?
Why Prefix Sum Array in DSA C++?
Imagine you have a long list of daily sales numbers and you want to quickly find the total sales between any two days.
Doing this by adding each day's sales every time you ask is like counting coins one by one every time you want to know your total money.
Manually adding numbers for each query is slow and tiring, especially if you have many queries.
It is easy to make mistakes by missing or double-counting numbers.
This wastes time and causes frustration.
A prefix sum array keeps a running total of sales up to each day.
This way, you can find the total sales between any two days by subtracting two prefix sums.
This makes queries very fast and simple.
int sumRange(int start, int end, vector<int>& sales) {
int total = 0;
for (int i = start; i <= end; i++) {
total += sales[i];
}
return total;
}vector<int> prefixSum(vector<int>& sales) {
vector<int> prefix(sales.size() + 1, 0);
for (int i = 0; i < sales.size(); i++) {
prefix[i + 1] = prefix[i] + sales[i];
}
return prefix;
}
int sumRange(int start, int end, vector<int>& prefix) {
return prefix[end + 1] - prefix[start];
}It enables lightning-fast queries for sums over any range, no matter how many times you ask.
In a fitness app, quickly showing total steps taken between any two dates without recalculating every time.
Manual summing is slow and error-prone for repeated queries.
Prefix sum array stores running totals to speed up range sum queries.
It makes repeated sum queries efficient and simple.
Practice
arr?Solution
Step 1: Understand prefix sum array definition
A prefix sum array stores cumulative sums, where each element at index i is the sum of all elements from index 0 to i in the original array.Step 2: Compare options with definition
Only An array where each element is the sum of all elements from the start up to that index inarrcorrectly describes this cumulative sum property. Other options describe different operations.Final Answer:
An array where each element is the sum of all elements from the start up to that index in arr -> Option CQuick Check:
Prefix sum = cumulative sum [OK]
- Confusing prefix sum with product or max operations
- Thinking prefix sum stores differences
- Assuming prefix sum resets at each index
prefix from an integer array arr of size n?Solution
Step 1: Check initialization of prefix array
Prefix sum starts with prefix[0] = arr[0], which is correct in options B, C, and D.Step 2: Verify loop and summation logic
prefix[0] = arr[0]; for(int i = 1; i < n; i++) prefix[i] = prefix[i-1] + arr[i]; correctly loops from i=1 to n-1 and adds prefix[i-1] + arr[i]. prefix[0] = 0; for(int i = 1; i <= n; i++) prefix[i] = prefix[i-1] + arr[i]; has wrong indexing and loop range. prefix[0] = arr[0]; for(int i = 0; i < n; i++) prefix[i] = prefix[i-1] + arr[i]; uses prefix[i-1] at i=0 which is invalid. prefix[0] = arr[0]; for(int i = 1; i < n; i++) prefix[i] = arr[i] - prefix[i-1]; subtracts instead of adding.Final Answer:
prefix[0] = arr[0]; for(int i = 1; i < n; i++) prefix[i] = prefix[i-1] + arr[i]; -> Option BQuick Check:
Initialize first, then add previous prefix + current [OK]
- Starting loop at 0 and accessing prefix[-1]
- Using wrong loop bounds (<= n instead of < n)
- Subtracting instead of adding elements
int arr[] = {2, 4, 6, 8};
int n = 4;
int prefix[4];
prefix[0] = arr[0];
for(int i = 1; i < n; i++) {
prefix[i] = prefix[i-1] + arr[i];
}
for(int i = 0; i < n; i++) {
std::cout << prefix[i] << " ";
}Solution
Step 1: Calculate prefix sums step-by-step
prefix[0] = 2
prefix[1] = prefix[0] + arr[1] = 2 + 4 = 6
prefix[2] = prefix[1] + arr[2] = 6 + 6 = 12
prefix[3] = prefix[2] + arr[3] = 12 + 8 = 20Step 2: Print prefix array elements
Output is: 2 6 12 20Final Answer:
2 6 12 20 -> Option AQuick Check:
Sum accumulates: 2, 6, 12, 20 [OK]
- Printing original array instead of prefix sums
- Incorrect addition order
- Off-by-one errors in loop
int arr[] = {1, 3, 5, 7};
int n = 4;
int prefix[4];
prefix[0] = arr[0];
for(int i = 1; i <= n; i++) {
prefix[i] = prefix[i-1] + arr[i];
}Solution
Step 1: Analyze loop bounds and array indexing
The loop runs with i from 1 to n inclusive (i <= n). Since arrays are 0-indexed, prefix[n] and arr[n] access out-of-bounds elements causing runtime error.Step 2: Correct loop condition
Changing loop condition to i < n ensures indices stay within valid range (0 to n-1).Final Answer:
Change loop condition to i < n to avoid out-of-bounds access -> Option AQuick Check:
Loop must stay within array size [OK]
- Using <= n causing out-of-bounds errors
- Starting loop at 0 and accessing prefix[-1]
- Incorrect initialization of prefix[0]
arr of size n, how can you use a prefix sum array to efficiently find the sum of elements between indices l and r (inclusive)?Solution
Step 1: Understand prefix sum usage for range queries
Prefix sum at index r gives sum from 0 to r. To get sum from l to r, subtract sum from 0 to l-1, which is prefix[l-1]. If l is 0, sum is prefix[r].Step 2: Apply formula for sum between l and r
Sum = prefix[r] - prefix[l-1] if l > 0, else prefix[r]. Other operations like addition, multiplication, or division are incorrect.Final Answer:
Sum = prefix[r] - prefix[l-1] if l > 0, else prefix[r] -> Option DQuick Check:
Range sum = prefix[r] - prefix[l-1] [OK]
- Adding prefix[l-1] instead of subtracting
- Using multiplication or division incorrectly
- Not handling case when l = 0
Ready to prove it?
Pass the test and this pattern moves unknown
