So far, we've learned arrays and how elements are stored in memory. We also learned that reading an element using its index is extremely fast. But what happens when someone asks questions like:
Find the sum of elements from index 2 to index 1000.
Add 5 to every element between index 50 and index 500.
Perform thousands of range queries and updates.
Can we simply use loops every time?
Yes, we can.
But imagine doing this hundreds of thousands of times.
It would become painfully slow.
This is where two amazing techniques come into the picture:
Prefix Sum → Makes range sum queries extremely fast.
Difference Array → Makes range updates extremely fast.
The infographic explains both concepts using a railway journey, where each station represents an array element. Let's understand everything step by step.
Why Do We Need Prefix Sum and Difference Array?
The compiler in the infographic says:
We use smart techniques to make queries and updates super fast!
Imagine you're working on a railway management system.
Every station has passengers.
Station
0 1 2 3 4 5
Passengers:
5 3 8 6 2 4
Now someone asks:
"How many passengers travelled from Station 2 to Station 5?"
If you calculate it every time using a loop,
8 + 6 + 2 + 4
that's fine for one query.
But what if there are 100,000 such queries?
A normal loop becomes too slow.
Prefix Sum solves this problem.
Similarly,
suppose you need to add:
+5
to every station between Station 2 and Station 5.
Updating every element individually works,
but again,
doing this thousands of times becomes expensive.
Difference Array solves that problem.
Part 1 — Prefix Sum
The infographic defines Prefix Sum as:
Running total of elements from the start to index i.
Think of Prefix Sum like your bank balance.
Every day,
your balance includes today's money plus everything before today.
It keeps accumulating.
Similarly,
Prefix Sum stores the running total.
Understanding the Original Array
The infographic starts with this array.
Index
0 1 2 3 4 5
Array
5 3 8 6 2 4
These represent passengers at each station.
Building the Prefix Sum Array
Now let's calculate the running total exactly as shown in the infographic.
First element
5
So,
Prefix[0] = 5
Next,
5 + 3 = 8
Therefore,
Prefix[1] = 8
Next,
8 + 8 = 16
Then,
16 + 6 = 22
Next,
22 + 2 = 24
Finally,
24 + 4 = 28
So the Prefix Sum array becomes:
5 8 16 22 24 28
Exactly as shown in the infographic.
Notice that every element stores the sum from the beginning up to that index.
Java Code for Building Prefix Sum
The infographic provides the logic. Here's the Java version.
int[] arr = {5, 3, 8, 6, 2, 4};
int[] prefix = new int[arr.length];
prefix[0] = arr[0];
for (int i = 1; i < arr.length; i++) {
prefix[i] = prefix[i - 1] + arr[i];
}
Let's understand it.
Initially,
prefix[0] = arr[0];
Because the first running total is simply the first element.
Then,
every new prefix value equals:
Previous Prefix + Current Element
So,
16 + 6 = 22
becomes
prefix[3] = prefix[2] + arr[3];
This loop builds the entire Prefix Sum array in O(n) time.
Range Sum Query
Now comes the real magic.
The infographic asks:
Find the sum from Station 2 to Station 5.
Normally,
we would calculate:
8 + 6 + 2 + 4 = 20
But Prefix Sum lets us do it instantly.
The infographic shows:
Prefix[5]
=
28
and
Prefix[1]
=
8
Now simply subtract.
28 - 8 = 20
That's the answer.
No loop.
No repeated addition.
Just one subtraction.
The Prefix Sum Formula
The general formula is:
Sum(L,R)
=
Prefix[R]
-
Prefix[L-1]
If the range starts from index 0,
then:
Sum = Prefix[R]
because there is nothing before index 0.
This formula allows every range query to be answered in O(1) time after the prefix array has been built.
Time Complexity of Prefix Sum
The infographic mentions:
Building Prefix:
O(n)
Range Query:
O(1)
This means we spend some time building the prefix array once,
and after that,
every range sum query becomes almost instantaneous.
Part 2 — Difference Array
Now let's move to the second half of the infographic.
Difference Array is the opposite idea.
Instead of answering range queries quickly,
it helps perform range updates efficiently.
The infographic defines it as:
Mark changes at boundaries, then build the final array.
This idea may seem strange at first,
but it's actually very clever.
The Problem
Suppose someone says:
Add 5 passengers to every station from Station 2 to Station 5.
The normal way would be:
Index
2
3
4
5
Add 5 to each one individually.
That requires multiple updates.
Instead,
Difference Array performs only two operations.
The Key Idea
The infographic highlights an important message:
Update only where changes BEGIN and END.
Instead of updating every element,
we simply mark the boundaries.
At the starting index,
add:
+5
After the ending index,
subtract:
-5
Everything in between automatically receives the update after one Prefix Sum pass.
This is the genius behind Difference Arrays.
Understanding the Example
The infographic shows the update:
Add +5 from Station 2 to Station 5.
Instead of modifying four elements,
the Difference Array stores:
Index
0 1 2 3 4 5 6
Difference Array
0 0 +5 0 0 0 -5
Notice,
only two positions changed.
Everything else remains untouched.
Building the Final Array
After all updates are marked,
we perform one Prefix Sum over the Difference Array.
The infographic shows the final updated array:
5
3
13
11
7
9
4
Let's verify.
Original:
5 3 8 6 2 4
Adding 5 from index 2 to index 5 gives:
5
3
13
11
7
9
Exactly as shown in the infographic.
Instead of updating four different positions,
we only marked two boundaries and reconstructed the final array.
Java Code for Difference Array
The infographic provides the algorithm.
Here's the Java version.
diff[L] += val;
if (R + 1 < diff.length)
diff[R + 1] -= val;
Let's understand it.
Suppose we want to add:
+5
from index
2
to
5
Then,
diff[2] += 5;
marks where the increment begins.
Next,
diff[6] -= 5;
marks where the increment stops.
Notice,
we didn't touch any element between 2 and 5.
Building the Final Array
After all updates are finished,
we rebuild the array.
for (int i = 1; i < diff.length; i++) {
diff[i] += diff[i - 1];
}
This Prefix Sum pass spreads the updates across the intended range.
The resulting array reflects all range updates at once.
Prefix Sum vs Difference Array
The infographic compares both techniques beautifully.
Prefix Sum
Best when:
Many range sum queries
Very few updates
Process:
Build once.
Answer queries instantly.
Difference Array
Best when:
Many range updates
Final array needed later
Process:
Mark updates.
Build once.
Get the final updated array.
Real-World Applications
The infographic lists several practical applications.
Range Sum Queries
Database analytics often calculate totals over a range of records.
Prefix Sum makes these operations fast.
Game Score Updates
Games frequently increase the scores of multiple players or regions simultaneously.
Difference Arrays handle such updates efficiently.
Analytics Dashboards
Business dashboards often calculate sales totals for different time periods.
Prefix Sum speeds up these calculations.
Sensor Data Processing
IoT devices collect continuous sensor readings.
Prefix Sums help compute averages and totals over time intervals efficiently.
Competitive Programming
Both Prefix Sum and Difference Arrays appear frequently in coding contests because they transform slow brute-force solutions into optimized ones.
Advantages
The infographic highlights why these techniques are so useful.
Prefix Sum
Extremely fast range queries.
Simple implementation.
One-time preprocessing.
Difference Array
Efficient range updates.
Only boundary changes are required.
Excellent for handling many updates before rebuilding the final array.
Time Complexity
Let's summarize the complexity of both techniques.
Prefix Sum
Operation | Complexity |
|---|---|
Build Prefix Array | O(n) |
Range Sum Query | O(1) |
Difference Array
Operation | Complexity |
|---|---|
One Range Update | O(1) |
Build Final Array | O(n) |
This is the biggest advantage.
Instead of updating every element inside a range,
Difference Array performs each update in constant time and applies all updates together later.
A Few Important Things to Know
There are a few important concepts that aren't explicitly shown in the infographic:
Prefix Sum is best for static arrays. If the array changes frequently after every query, rebuilding the prefix array repeatedly becomes inefficient.
Difference Arrays are usually combined with a final Prefix Sum pass. On their own, they only store boundary changes.
For problems involving both frequent updates and frequent range queries, advanced data structures like Fenwick Trees (Binary Indexed Trees) or Segment Trees are often used because they support both operations efficiently.
Difference Arrays work with multiple updates. You can perform hundreds or thousands of range updates first and rebuild the final array only once.
Conclusion
Prefix Sum and Difference Array are two powerful optimization techniques that solve different types of problems. Prefix Sum is designed to answer range sum queries instantly after a one-time preprocessing step, while Difference Array is designed to perform range updates efficiently by marking only the start and end of each update. Although they are based on opposite ideas, both techniques rely on cumulative sums and significantly reduce unnecessary work. Mastering these two concepts will help you solve many array-based problems efficiently in coding interviews and competitive programming.
Quick Revision
Concept | Remember |
|---|---|
Prefix Sum | Running total from index 0 to index i. |
Prefix Formula | Sum(L,R) = Prefix[R] − Prefix[L−1] |
Prefix Build | O(n) |
Range Sum Query | O(1) |
Difference Array | Stores only boundary changes for range updates. |
Range Update | Add at L, subtract at R + 1. |
Difference Update | O(1) per update |
Final Build | One Prefix Sum pass → O(n) |
Use Prefix Sum | Many range sum queries |
Use Difference Array | Many range updates |
