Skip to lesson

Difference arrays

Prefix sums answer q range queries in O(1) each after one O(n) build pass. What if you have the dual problem: applying u range updates ("add val to every element in arr[left .. right]") before reading the final array? A difference array records each range update in O(1) time and rebuilds the final values with one O(n) prefix sum pass.

Range add in O(1)

A difference array records only the changes between neighbours, so adding a value to a whole range takes O(1) and the final array is rebuilt with one prefix sum.

Suppose an array starts as all zeroes [0, 0, 0, 0, 0] and you receive u updates of the form (left, right, val), each adding val to every index from left to right inclusive.

  1. Allocate int[] diff = new int[n + 1] (one extra slot at index n).
  2. For each update [left, right, val]:
  3. diff[left] += val;
  4. diff[right + 1] -= val;

Example 1 · Brute force: add to every index of every range (O(n · u) time, O(1) extra space)

RangeAdditionBrute.javaJava
import java.util.Arrays;
public class RangeAdditionBrute {    public static int[] getModifiedArray(int length, int[][] updates) {        int[] result = new int[length];        for (int[] u : updates) {            for (int i = u[0]; i <= u[1]; i++) {                result[i] += u[2];            }        }        return result;    }
    public static void main(String[] args) {        int[][] updates = {{1, 3, 2}, {2, 4, 3}, {0, 2, -2}};        int[] finalArr = getModifiedArray(5, updates);        System.out.println(Arrays.toString(finalArr));    }}
Output
[-2, 0, 3, 5, 3]

What this code does

  • Each update loops over its whole range, so u updates on an array of length n cost up to n × u additions.
  • Only the final array is needed, not the array between updates. A range update can therefore be recorded as two markers and resolved once at the end.

Example 2 · Optimal: difference array, two markers per update (O(n + u) time, O(n) space)

RangeAdditionDemo.javaJava
import java.util.Arrays;
public class RangeAdditionDemo {    public static int[] getModifiedArray(int length, int[][] updates) {        int[] diff = new int[length + 1];        for (int[] u : updates) {            int left = u[0], right = u[1], val = u[2];            diff[left] += val;            diff[right + 1] -= val;        }        int[] result = new int[length];        int running = 0;        for (int i = 0; i < length; i++) {            running += diff[i];            result[i] = running;        }        return result;    }
    public static void main(String[] args) {        int[][] updates = {{1, 3, 2}, {2, 4, 3}, {0, 2, -2}};        int[] finalArr = getModifiedArray(5, updates);        System.out.println(Arrays.toString(finalArr));    }}
Output
[-2, 0, 3, 5, 3]

What this code does

  • After {1,3,2}, {2,4,3}, and {0,2,-2}, diff[0..5] is [-2, 2, 3, 2, -2, -3].
  • Sweeping the running prefix sum over indices 0..4 yields [-2, 0, 3, 5, 3].
  • Why it is faster: each update costs two array writes whatever its length, and one prefix-sum pass at the end rebuilds every value.

Looping from left to right for each update takes O(n · u) time.

Instead, imagine a difference array diff where diff[i] represents "how much the running total changes when we step onto index i":

  • When we enter the range at left, the running total should jump up by +val: diff[left] += val.
  • When we step past the end of the range at right + 1, that boost ends, so the running total should drop back down by -val: diff[right + 1] -= val.

Allocating diff = new int[n + 1] (with one extra sentinel slot at index n) lets you write diff[right + 1] -= val unconditionally even when right == n - 1!

Find the bug

Find the difference-array bug

Tap the line that is wrong.

The values stay too large after the range ends. Which line is wrong?

Round 1 of 2

Rebuilding values with a prefix sum

Difference arrays and prefix sums are mathematical inverses (like differentiation and integration in calculus).

RebuildFromDiff.javaJava
import java.util.Arrays;
public class RebuildFromDiff {    public static void main(String[] args) {        int n = 5;        int[] diff = new int[n + 1];        diff[1] += 2; diff[4] -= 2;          // add 2 to indexes 1..3        diff[2] += 3; diff[5] -= 3;          // add 3 to indexes 2..4        for (int i = 1; i < n; i++) {            diff[i] += diff[i - 1];          // prefix sum rebuilds the values        }        System.out.println(Arrays.toString(Arrays.copyOf(diff, n)));    }}
Output
[0, 2, 5, 5, 3]

Once all u range updates have been recorded as +val and -val markers in diff, taking the prefix sum of diff over indices 0 .. n - 1 reconstructs the exact final value at every index!

Why? Because for any index i, the prefix sum diff[0] + diff[1] + ... + diff[i] includes +val for every range that started at or before i (left <= i) and includes -val (canceling +val) for every range that already ended before i (right + 1 <= i, i.e., right < i). Only the ranges currently covering i (left <= i <= right) remain active!

  • Each range update [left, right, val] costs 2 array operations: O(1) time.
  • Rebuilding the final array of length n costs 1 prefix sum pass: O(n) time.
  • Total time for u updates on an array of size n: O(n + u) instead of O(n * u).
If the array starts with non-zero initial values initial[0..n-1], you can either initialize diff from initial, or keep diff starting at all zeroes (recording only the net changes) and add initial[i] + runningDiff at the end.

Real world: bookings per day

Difference arrays appear in scheduling, capacity planning and event timelines.

Example 3 · Corporate Flight Bookings (1-indexed inclusive ranges)

FlightBookingsDemo.javaJava
import java.util.Arrays;
public class FlightBookingsDemo {    public static int[] corpFlightBookings(int[][] bookings, int n) {        int[] diff = new int[n + 1];        for (int[] b : bookings) {            int first = b[0] - 1;            int last = b[1] - 1;            int seats = b[2];            diff[first] += seats;            diff[last + 1] -= seats;        }        int[] answer = new int[n];        int running = 0;        for (int i = 0; i < n; i++) {            running += diff[i];            answer[i] = running;        }        return answer;    }
    public static void main(String[] args) {        int[][] bookings = {{1, 2, 10}, {2, 3, 20}, {2, 5, 25}};        System.out.println(Arrays.toString(corpFlightBookings(bookings, 5)));    }}
Output
[10, 55, 45, 25, 25]

What this code does

  • Converting 1-indexed [first, last] to 0-indexed [first - 1, last - 1] makes last + 1 equal to b[1].
  • Flight 2 (index 1) is covered by all three bookings: 10 + 20 + 25 = 55 seats.

Example 4 · Car Pooling (half-open intervals [from, to))

CarPoolingDemo.javaJava
public class CarPoolingDemo {    public static boolean carPooling(int[][] trips, int capacity) {        int maxLocation = 0;        for (int[] t : trips) {            maxLocation = Math.max(maxLocation, t[2]);        }        int[] diff = new int[maxLocation + 1];        for (int[] t : trips) {            int passengers = t[0], from = t[1], to = t[2];            diff[from] += passengers;            diff[to] -= passengers;        }        int onboard = 0;        for (int d : diff) {            onboard += d;            if (onboard > capacity) {                return false;            }        }        return true;    }
    public static void main(String[] args) {        int[][] trips = {{2, 1, 5}, {3, 3, 7}};        System.out.println("Capacity 4: " + carPooling(trips, 4));        System.out.println("Capacity 5: " + carPooling(trips, 5));        int[][] dropAndPick = {{3, 1, 5}, {3, 5, 8}};        System.out.println("Drop & pick at km 5 (cap 3): " + carPooling(dropAndPick, 3));    }}
Output
Capacity 4: false
Capacity 5: true
Drop & pick at km 5 (cap 3): true

What this code does

  • Because passengers drop off at 'to', subtracting at diff[to] (not to + 1) allows another group to board at 'to' without exceeding capacity.
  • In dropAndPick at km 5, diff[5] receives -3 and +3 = 0, so onboard stays at 3 <= 3.
  • Corporate Flight Bookings: Each booking reserves seats across flights first .. last (1-indexed, inclusive). Both first and last are part of the reservation, so we add +seats at first - 1 and -seats at last.
  • Car Pooling & Hotel Bookings: A trip picks up numPassengers at kilometer from and drops them off at kilometer to. Because passengers get out at to (so [from, to) is half-open!), we add +numPassengers at diff[from] and -numPassengers at diff[to] (not to + 1!). Then we sweep the prefix sum and check if any point exceeds vehicle capacity.
  • Inclusive interval [left, right]: diff[left] += val; diff[right + 1] -= val;.
  • Half-open interval [from, to) (e.g., hotel check-out or car drop-off at 'to'): diff[from] += val; diff[to] -= val;.

Next step

Check your understanding

10 quick questions