DEV Community

Nithya Dharshini official
Nithya Dharshini official

Posted on

Understanding Prefix Sum with a Practical Example (Pocket Money Tracker)

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]

Enter fullscreen mode Exit fullscreen mode

Result:

Day Prefix Sum
0 10
1 30
2 35
3 50
4 80
5 90
6 140

So the prefix array becomes: -> [10, 30, 35, 50, 80, 90, 140]

Step 2: Answer Queries Instantly

Now suppose we want the total from Day 2 to Day 4.

Instead of adding: 5 + 15 + 30

We simply do: prefix[4] - prefix[1]

Which gives: 80 - 30 = 50 (Instant answer ^-^)

C++ Implementation

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v = {10, 20, 5, 15, 30, 10, 50};
    int L = 2, R = 4; 

    vector<int> pref(v.size());
    pref[0] = v[0];

    for(int i = 1; i < v.size(); ++i) {
        pref[i] = pref[i-1] + v[i];
    }

    int result = (L == 0) ? pref[R] : pref[R] - pref[L-1];

    cout << "Total spending: " << result << endl;

    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Output: -> 50

Why Prefix Sum is Powerful

Without Prefix Sum: Each query → O(n)
With Prefix Sum: Each query → O(1)

This is extremely useful when we have many range queries.

Key Takeaway

Prefix Sum is useful when:

  • You need sum of elements in a range
  • There are multiple queries
  • You want fast lookup instead of repeated loops

It is widely used in:

  • Data analytics
  • Financial calculations
  • Competitive programming
  • Range query problems

Top comments (0)