AlgoTales · Roadmap

Difference array

Advanced · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A difference array lets you add a value to a whole range by only touching its two ends, then rebuilds all the real values at once with one final running total. It is the mirror image of the prefix sum, and perfect when many range updates come first and reading comes later.

Practical use cases

  • Web app: Hall bookings across many dates. A wedding-hall site has 5,000 bookings each covering several days, and the owner wants the number of bookings on each day of the year. Adding one to every day of every booking is slow. Marking plus one on the first day and minus one after the last, then taking a running total, gives every day's count in one pass.
  • Web app: Bulk discounts over price bands or dates. A promotion tool applies thousands of "10 rupees off for items from position 100 to 400" rules. Marking range ends and adding up once gives the final discount at every position. The promotion tool shows final discounts straight away, even when thousands of rules overlap.
  • Web app: Seat occupancy in a bus or flight booking. A reservation system counts seats taken on each leg of a journey. Each ticket adds one to the legs between boarding and exit by marking just two points. A booking screen shows seats taken on each leg of the trip without looping over every ticket and every leg.
  • System: Sensor data and game maps. Weather systems and game engines add effects (heat, damage) over areas by marking only the two ends of each area, then compute the final map once at the end. Each update touches only two places, however big the area is.

The story: The Wedding Hall Chair Orders

Zoya's cousin was getting married, and the wedding hall had a long row of chairs. The caterer kept phoning with orders: "Put one extra cushion on chairs 40 to 180." "Remove two cushions from chairs 100 to 150." Each call touched dozens of chairs, and there were 500 calls!

Kabir ran up and down the row fixing every chair after every call and was exhausted by lunch. Mira had a better idea. "For each call, don't visit all the chairs. Stick a green flag at the first chair saying: from here, one more cushion. Stick a red flag just after the last chair saying: stop, take it back."

At the very end, walk the row once, carrying a running count: green flag, count goes up; red flag, count goes down. The count at each chair is exactly its cushions. 500 calls, each only 2 flags, and one walk.

The smell: "many updates, each adds a value to a whole range, and we read the answer at the end". That is the difference array: it records changes, and a prefix sum turns the changes into real values.

How to spot this problem, and where you need it

You must add a value to many ranges of a list, and a loop over every position of every range makes the total work huge.

Signs you need it

  • The task is "add x to all items from L to R", repeated thousands of times, and the final array is only read at the end.
  • Your update function has a for-loop from L to R, and the update count is large.
  • You are counting how many ranges (bookings, sessions, offers) cover each position.

Where to use it in a project

  • Daily occupancy counts for hotels, halls, buses and seats built from many bookings.
  • Bulk price or discount rules that apply to ranges of products or dates.
  • Heat maps and grids built from many rectangular updates, then read once.

The solution

Make an array of zeros. For each update from L to R adding v, add v at position L and subtract v at position R plus one. When all updates are in, walk through the array once keeping a running total; that running total at each position is its final value. Each update costs two operations regardless of the range size.

Payoff: Before: 5,000 bookings times about 30 days each, 150,000 edits. After: 10,000 edits and one pass.

Explain it like I am 8

A teacher says "everyone from row 2 to row 5, take one extra biscuit". Instead of walking to every child, she puts a "+1" sticker on row 2 and a "-1" sticker after row 5. Later, a helper walks the line adding up stickers as he goes. Each child gets exactly the right number.

How it works, step by step

  1. Clues: "add x to every element from l to r", "many range updates", "apply all, then report". Think difference array.
  2. Make a marks array of size n+1 (the extra slot catches the "stop" mark of the last range), all zeros.
  3. For each update (l, r, v): diff[l] += v and diff[r + 1] -= v. Two writes, no matter how long the range.
  4. When all updates are in, walk left to right keeping a running total of the marks: run += diff[i].
  5. The running total at each place is the final value there. It is the prefix sum in reverse: prefix sums read ranges fast, difference arrays write ranges fast.

The code in four languages

PHP

<?php
// Range Addition: start with n zeros, apply many "add v to l..r" updates
function rangeAdd(int $n, array $updates): array {
    $diff = array_fill(0, $n + 1, 0);   // one extra slot for the "stop" mark
    foreach ($updates as [$l, $r, $v]) {
        $diff[$l] += $v;                // from l onward, v more
        $diff[$r + 1] -= $v;            // after r, take it back
    }
    $result = [];
    $running = 0;
    for ($i = 0; $i < $n; $i++) {
        $running += $diff[$i];          // prefix sum of the marks
        $result[] = $running;
    }
    return $result;
}
$updates = [[1, 3, 2], [2, 4, 3], [0, 2, -2]];
echo implode(", ", rangeAdd(5, $updates));   // -2, 0, 3, 5, 3

JavaScript

// Range Addition: start with n zeros, apply many "add v to l..r" updates
function rangeAdd(n, updates) {
  const diff = new Array(n + 1).fill(0);   // one extra slot for the "stop" mark
  for (const [l, r, v] of updates) {
    diff[l] += v;                          // from l onward, v more
    diff[r + 1] -= v;                      // after r, take it back
  }
  const result = [];
  let running = 0;
  for (let i = 0; i < n; i++) {
    running += diff[i];                    // prefix sum of the marks
    result.push(running);
  }
  return result;
}
const updates = [[1, 3, 2], [2, 4, 3], [0, 2, -2]];
console.log(rangeAdd(5, updates).join(", "));   // -2, 0, 3, 5, 3

Java

import java.util.*;

public class Main {
    // Range Addition: start with n zeros, apply many "add v to l..r" updates
    static int[] rangeAdd(int n, int[][] updates) {
        int[] diff = new int[n + 1];       // one extra slot for the "stop" mark
        for (int[] u : updates) {
            int l = u[0], r = u[1], v = u[2];
            diff[l] += v;                  // from l onward, v more
            diff[r + 1] -= v;              // after r, take it back
        }
        int[] result = new int[n];
        int running = 0;
        for (int i = 0; i < n; i++) {
            running += diff[i];            // prefix sum of the marks
            result[i] = running;
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] updates = {{1, 3, 2}, {2, 4, 3}, {0, 2, -2}};
        System.out.println(Arrays.toString(rangeAdd(5, updates)));   // [-2, 0, 3, 5, 3]
    }
}

Go

package main

import "fmt"

// rangeAdd starts with n zeros and applies many "add v to l..r" updates.
func rangeAdd(n int, updates [][3]int) []int {
	diff := make([]int, n+1) // one extra slot for the "stop" mark
	for _, u := range updates {
		l, r, v := u[0], u[1], u[2]
		diff[l] += v   // from l onward, v more
		diff[r+1] -= v // after r, take it back
	}
	result := make([]int, n)
	running := 0
	for i := 0; i < n; i++ {
		running += diff[i] // prefix sum of the marks
		result[i] = running
	}
	return result
}

func main() {
	updates := [][3]int{{1, 3, 2}, {2, 4, 3}, {0, 2, -2}}
	fmt.Println(rangeAdd(5, updates)) // [-2 0 3 5 3]
}

Time: O(n + q) · Extra space: O(n). Each of the q updates costs two writes, plus one pass over n places; doing every update naively would cost O(n × q).

Watch out for

  • Making the array only size n, then crashing or losing the stop mark when r + 1 equals n.
  • Reading values in the middle of the updates. The marks only become real values after the final running-total pass.
  • Writing diff[r] -= v instead of diff[r + 1], which removes the value one place too early.

Quick check

  1. An update says "add 5 to indexes 2..6". What do you write in the difference array?
    • +5 at every index 2..6
    • +5 at 2 and -5 at 6
    • +5 at 2 and -5 at 7
  2. How do you get the real values at the end?
    • Sort the marks
    • Running total (prefix sum) of the marks
    • Multiply the marks
  3. Which clue points to a difference array?
    • "Many updates add a value to whole ranges"
    • "Find two numbers that add to target"
    • "Longest increasing run"