Lesson 7 · Linear structures

Difference Arrays

A difference array stores the change from each element to the next instead of the values. Adding a number to a whole range then takes two writes, and one running-total pass at the end turns the marks back into the finished array.

Difference Arrays concept diagramA visual explanation of the layout and operations shown in this lesson.range update: mark +3 at the start and −3 after the end00+31020304−35range startsjust past the endone prefix pass applies the update to every covered index
1

Many Overlapping Range Updates

The setting is always the same: an array of n values and a list of q operations, each adding some v to every element from index l to index r. Produce the final array.

The direct way loops from l to r for each operation. A wide range costs O(n), so q operations cost O(n · q). With 100,000 values and 100,000 operations, that is up to ten billion additions.

Most of that work is wasted. Overlapping ranges add to the same cells again and again, and only the final value of each cell matters.

A difference array changes what is stored. It records how each element differs from the one before it, so a range update only touches the two places where the change starts and stops. Each update becomes O(1), and one O(n) pass at the end rebuilds every value: O(n + q) in total.

The catch: all updates must be known before any value is read. The technique batches updates and rebuilds once. If updates and reads take turns, use a Fenwick tree or a segment tree instead.

  • Typical sign: many range additions, and the answer is only needed at the end
  • Reads in between updates break it, because each read would need a full rebuild
  • Use 64-bit totals when many large updates can stack on one cell
2

Storing Changes Instead of Values

Build D from an array A with D[0] = A[0] and D[i] = A[i] − A[i−1] for every later index. Each entry is the step up or down from the previous element.

For A = [3, 3, 5, 5, 5, 2], D = [3, 0, 2, 0, 0, −3]. A 0 means no change. Runs of equal values turn into zeros, and only the edges of each run carry a number.

To get A back, keep a running total: A[i] = D[0] + D[1] + … + D[i]. In place, that is D[i] += D[i − 1] from left to right.

So D and prefix sums undo each other. Prefix sums turn values into totals so that range reads are O(1); D turns values into steps so that range updates are O(1).

Most problems start from an array of zeros, and then D starts as zeros too. Give it n + 1 slots, not n. An update that ends at the last index writes its closing mark into the extra slot, so no bounds check is needed.

  • Starting from real data, build D first; starting from zeros, D is all zeros
  • The spare slot is written to but never read during the rebuild
  • Rebuilding twice by mistake turns values into prefix sums of values
3

The Two-Write Update

  1. Make D with n + 1 zeros (or build it from A).
  2. For each update (l, r, v): D[l] += v and D[r + 1] −= v. O(1) each.
  3. Keep a running total from index 0 to n − 1; A[i] is the total after adding D[i]. O(n) once.

To add v to every element from l to r inclusive, make two writes: D[l] += v and D[r + 1] −= v.

Why it works: the rebuild is a running total, so +v at l lifts every element from l to the end. The −v at r + 1 cancels it from that point on, so the lift covers exactly l to r. Nothing in between is touched; those cells inherit the change from the running total.

Updates combine by plain addition, in any order. Three overlapping ranges write six marks, and the running total at each cell adds up every range that covers it. No case analysis is needed for overlaps.

This difference array technique is the standard answer to a range update problem where every update comes before the reads.

Difference array against the alternatives
Loop over the rangeDifference arrayFenwick / segment tree
Range updateO(n)O(1)O(log n)
Read a valueO(1)Only after the O(n) passO(log n)
Total for q updatesO(n · q)O(n + q)O(q log n)
Reads between updates?YesNoYes
  • D[r] −= v instead of D[r + 1] −= v drops the last cell of every range
  • Returning D without the rebuild gives numbers that look plausible and are wrong
  • 1-based ranges (as in many problem statements) need l − 1 and r, or an array of n + 2
Key reference

Terms, operations, and practical uses

Core operations

  • Range additionAdd a value v to every element from index l to index r.
  • Boundary marksD[l] += v and D[r + 1] −= v record the whole range update in two O(1) writes.
  • RebuildA running total over D gives the final value of every element in one O(n) pass.

State and timing

  • Offline updatesAll updates are applied first and the values are read only after the rebuild.
  • Online queriesUpdates and reads interleave; the marks would need an O(n) rebuild per read, so use a tree.
  • Sweep lineThe same +v / −v events, sorted by position, when coordinates are too large for an array.

Use cases

  • Interval overlap+1 at each start and −1 after each end; the running total counts the intervals covering each point.
  • Flight bookingsSeat counts added over ranges of flight legs, read once at the end.
  • 2D difference arrayFour marks per rectangle, then running totals along rows and down columns.
Implementation

Code in Python, C++ and Java

N = 5
D = [0] * (N + 1)

# Add 10 to [1, 3]
D[1] += 10
D[3+1] -= 10

# Subtract 5 from [2, 4]
D[2] -= 5
D[4+1] += 5

# Reconstruct
A = [0] * N
current = 0
for i in range(N):
    current += D[i]
    A[i] = current

print('Final array:', A)
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int N = 5;
    vector<int> D(N + 1, 0);

    // Add 10 to [1, 3]
    D[1] += 10;
    D[3+1] -= 10;

    // Subtract 5 from [2, 4]
    D[2] -= 5;
    D[4+1] += 5;

    // Reconstruct
    vector<int> A(N, 0);
    int current = 0;
    for (int i = 0; i < N; i++) {
        current += D[i];
        A[i] = current;
    }
    cout << "Final array: [";
    for (int i = 0; i < N; i++) { if (i) cout << ", "; cout << A[i]; }
    cout << "]\n";
}
class Main {
    public static void main(String[] args) {
        int N = 5;
        int[] D = new int[N + 1];

        // Add 10 to [1, 3]
        D[1] += 10;
        D[4] -= 10;

        // Subtract 5 from [2, 4]
        D[2] -= 5;
        D[5] += 5;

        // Reconstruct
        int[] A = new int[N];
        int current = 0;
        for (int i = 0; i < N; i++) {
            current += D[i];
            A[i] = current;
        }
        System.out.println("Final array: " + java.util.Arrays.toString(A));
    }
}
Watch it run

Step through it

Running on 5 zeros; add 10 to [1, 3]; subtract 5 from [2, 4]

startD (marks)A (values)000102030405 (spare)01234updates: +10 on [1, 3], then −5 on [2, 4]
Step 1

Six slots for five values

The array has 5 values, all 0, so D starts as zeros too. D gets one extra slot at index 5. An update that ends at the last index writes its closing mark there, so no write ever needs a bounds check.

Output
1 / 13
4

Rectangles in a Grid

  1. D[r1][c1] += v
  2. D[r1][c2 + 1] −= v and D[r2 + 1][c1] −= v
  3. D[r2 + 1][c2 + 1] += v

A 2D difference array adds v to every cell of the rectangle from (r1, c1) to (r2, c2) with the four marks listed, instead of a loop over the rectangle.

The two −v marks each cancel the change past one edge. Past both edges, the corner has been cancelled twice, so the +v at (r2 + 1, c2 + 1) puts one back. This is inclusion–exclusion, the same correction used by 2D prefix sums in Range Sum Query 2D.

Rebuild with a running total along every row, then down every column. Example on a 3 × 3 grid: add 1 to the rectangle (0, 0)–(1, 1). The marks are +1 at (0, 0), −1 at (0, 2), −1 at (2, 0) and +1 at (2, 2). Row totals give rows [1, 1, 0], [0, 0, 0] and [−1, −1, 0]; column totals then give [1, 1, 0], [1, 1, 0] and [0, 0, 0]. Exactly the 2 × 2 top-left block is 1.

Each rectangle costs O(1), and the rebuild costs O(rows × columns) once.

  • Allocate (rows + 1) × (columns + 1) so the far marks always fit
  • Rows first then columns, or columns first then rows: the result is the same
  • Forgetting the corner mark leaves −v everywhere below and right of the rectangle
5

Where It Shows Up

Bookings and occupancy. How many seats are booked on each flight leg, or how many meetings use each hour: every booking is a range and the answer is the total per position. LeetCode 1109 Corporate Flight Bookings is the textbook case.

Most-overlapped point. Put +1 at each interval start and −1 just past each end, then take the running total; its maximum is the largest overlap. This is a sweep line, and on small integer coordinates the difference array is all it needs.

Large or sparse coordinates. When positions are timestamps, an array indexed by position is too big. Keep the same +v and −v events in a list, sort them by position, and sweep. Same idea, different container.

In competitive programming the technique is often called the imos method, after the Japanese programmer who popularised it, and the 2D and higher-dimensional versions appear under that name in editorials.

Choosing the tool comes down to one question: are all updates known before the first read? If yes, two marks per update and one rebuild pass is the simplest and fastest choice. If reads and updates interleave, a Fenwick tree handles sums and a segment tree with lazy propagation handles the rest.

  • Car pooling and meeting-room problems are range updates in disguise
  • Interval end conventions matter: closed [l, r] marks r + 1, half-open [l, r) marks r
  • A Fenwick tree storing a difference array gives range updates with point reads online