Prefix Sum is a simple but powerful technique used in many array problems instead of recalculating sums repeatedly, we store running totals to answer queries instantly.Let’s understand this using a small real-life example.
The Scenario: Pocket Money Tracker
Imagine you are tracking your daily expenses for a week.You store them in an array:
expenses = [10, 20, 5, 15, 30, 10, 50]
Each number represents the amount spent on that day.
Day
Expense
0
10
1
20
2
5
3
15
4
30
5
10
6
50
Now your friend asks questions like:
How much did you spend from Day 2 to Day 4?
What was the total from Day 0 to Day 5?
If you calculate this every time using a loop, it becomes inefficient. This is where Prefix Sum helps.
Step 1: Build the Prefix Sum Array
Prefix sum stores the running total of expenses.
Formula:
prefix[i] = prefix[i-1] + expenses[i]
Result:
Day
Prefix Sum
0
10
1
30
2
35
3
50
4
80
5
90
6
140
So the prefix a
Discussion
Leave the first comment
Be the first to leave a mark on this discussion.