Difference arrays

Introduction

A prefix sum answers many range queries fast. Its mirror image answers many range updates fast. Suppose you must add 5 to every element of a[l..r], and there are 10⁵ such updates on an array of 10⁵ elements. Looping over each range is O(n) per update and far too slow.

A difference array records only where the change starts and where it stops. You do all the updates in O(1) each, then rebuild the real array once at the end.

How it works

Let diff[i] be how much a[i] differs from a[i - 1]. To add v to a[l..r], the values jump up by v at position l and drop back by v just after r:

diff[l]     += v
diff[r + 1] -= v

That is two operations whatever the length of the range. When all updates are done, a running sum of diff gives the final array: a[i] = diff[0] + diff[1] + ... + diff[i]. This is a prefix sum, so the difference array is the exact reverse of the prefix-sum idea.

Make diff one cell longer than the array, so that diff[r + 1] is always a valid index, even when r is the last position.

Counting overlaps

Intervals are range updates too. If a guest is in a hotel from day a to day b, add 1 to a..b. After all guests, the running sum at each day is how many guests are present. The busiest day is the position of the largest running sum. This works for any "how many things cover this point" question, with no nested loops.

Two dimensions

For a grid, adding to a rectangle changes four corners: +v at the top-left, -v just right of the top-right, -v just below the bottom-left, and +v diagonally past the bottom-right corner. A prefix sum along rows and then along columns restores the grid.

Order matters. Do all the updates first, then one pass to rebuild. If you must read values between updates, a difference array is the wrong tool: it only helps when the questions come after the updates.

Example

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

int main() {
    int n = 8;
    vector<int> diff(n + 1, 0);
    int ops[3][3] = {{1, 4, 5}, {3, 6, 2}, {0, 7, 1}};   // l, r, v (0-based, both ends included)
    for (int k = 0; k < 3; k++) {
        int l = ops[k][0], r = ops[k][1], v = ops[k][2];
        diff[l] += v;
        diff[r + 1] -= v;
    }
    int cur = 0;
    for (int i = 0; i < n; i++) {
        cur += diff[i];
        cout << cur << " ";
    }
    cout << "\n";
    return 0;
}
Open in compiler

The program starts with eight zeros and applies three range additions using only two writes each. A single running sum then prints the final array.

Line by line

  • vector<int> diff(n + 1, 0) has one spare cell for r + 1.
  • Each operation does diff[l] += v and diff[r + 1] -= v.
  • cur += diff[i] is the running sum, which is the real value of a[i].
  • The first operation adds 5 to positions 1 to 4, the second adds 2 to 3 to 6, and the third adds 1 to all eight.

Expected result

1 6 6 8 8 3 3 1 

In the real world

Difference arrays count how many meetings overlap (room booking), how many people are online at each minute (from login and logout times), and how many layers cover each pixel. In image and map software the 2D version paints many rectangles at once. The same sweep idea appears whenever events have a start and an end.

Common mistakes

  • Forgetting the spare cell and writing diff[n] out of range when r = n - 1.
  • Subtracting at r instead of r + 1, which leaves the last element of the range out.
  • Mixing 0-based and 1-based positions between the input and the array.
  • Reading values between updates instead of after them.
  • Using int when many updates can add up past 2 × 10⁹.

Best practices

  • Allocate n + 2 cells and use 1-based positions, so r + 1 never overflows the array.
  • Write the two update lines once in a short function.
  • Rebuild with a running variable instead of a second array when you can.
  • Test an update that covers the whole array and one that covers a single cell.
  • Use long long when the total can be large.

Summary

A difference array stores changes instead of values. A range update becomes two writes, and one running sum afterwards produces the final array. It is the partner of the prefix sum, and the quick way to count how many intervals cover each point.

Quick check

1. To add v to a[l..r], which two writes does a difference array need?
2. How do you get the final array from diff?
3. What does the running sum of intervals marked +1 at a and -1 at b + 1 tell you?
4. Why does diff have n + 1 cells and not n?

Key takeaways

  • To add v to a[l..r], do diff[l] += v and diff[r + 1] -= v
  • The running sum of diff gives back the real array
  • All updates cost O(1) and one O(n) pass finishes the job
  • Intervals that cover points are counted with the same trick

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.