Difference arrays
Intermediate · 9 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 stretch of a list by changing just two spots: a plus where the stretch starts and a minus just after it ends. After all updates, one pass rebuilds every final value, so many range updates become cheap.
Practical use cases
- Web app: Hotel rooms booked each night. A booking site gets thousands of reservations, each covering several nights. Adding one to every night of every stay is slow. Instead, it adds one on check-in day and subtracts one on checkout day, then a single pass shows how many rooms are booked for each night of the year.
- Web app: Seat or bus occupancy. A bus app has passengers who board at one stop and leave at another. Marking plus one at boarding and minus one at leaving, then walking along the route once, gives the passengers on board between every pair of stops, helping decide where to add a bus.
- System: Calendar overlaps and brightness. Meeting-room schedulers use plus and minus marks to find the busiest moment, and photo editors brighten a stripe of pixels by marking only its two edges. The shape of work is the same: lots of range changes, then one read.
The story: The Gardener and the Rain Stones
Old Gardener Hari looked after a long row of plant beds behind the school. Each morning the principal sent notes: "Give 2 mugs of water to beds 1 to 3." "Give 3 mugs to beds 2 to 5." Hari had hundreds of such notes and thousands of beds. He walked along every bed for every note, and his legs were done by lunch.
His grandson Aarav, who liked clever shortcuts, said, "Dada, do not water anything yet. For each note just put two small stones on the ground: a green stone at the first bed, meaning rain starts here, and a red stone just after the last bed, meaning rain stops here."
After all the notes were done, Hari walked down the row once. He kept count in his head: green stone, add the amount; red stone, take it away. At each bed the number in his head was exactly how much water it needed. One walk, all notes done!
Those stones are a difference array. It records only where a change starts and stops, and a single running total later turns the marks into the real values. It is the opposite twin of prefix sums.
How to spot this problem, and where you need it
Many updates each affect a range of positions, like adding to all days between two dates, and looping over every day for every update makes the job painfully slow.
Signs you need it
- The input is a long list of ranges, such as from-date and to-date, each adding or subtracting a value.
- Your code has a loop over updates and, inside it, a loop over each position in the range.
- You only need the final values after all updates, not after every single update.
Where to use it in a project
- Reservation, occupancy and capacity reports across days, seats or hours.
- Bulk discount or price-change rules that apply to date ranges or product id ranges.
The solution
Make a list of zeros. For every update that adds v from position a to position b, add v at a and subtract v at b plus one. Do this for all updates, which takes two steps each. Finally, walk through the list keeping a running total: each running total is the final value for that position. The cost no longer depends on how long each range is.
Payoff: Before: 10,000 bookings times 7 nights is 70,000 updates. After: 20,000 quick marks and a single pass over 365 days.
Explain it like I am 8
You are colouring a long paper strip. Instead of colouring each square for every instruction, you just write "+2" where the colour starts and "-2" where it stops. At the end you walk along the strip adding up your notes, and the colours appear.
How it works, step by step
- Make a
diffarray one box longer than the data, all zeros. - For each update (l, r, v): do
diff[l] += v(the change begins). - Then do
diff[r + 1] -= v(the change ends). This is why we keep a spare box. - After all updates, sweep left to right keeping a running total of
diff. - The running total at index i is the final value of bed i.
The code in four languages
PHP
<?php
// Apply many "add v to every index from l to r" updates quickly
function applyUpdates(int $n, array $updates): array {
$diff = array_fill(0, $n + 1, 0); // one spare box at the end
foreach ($updates as [$l, $r, $v]) {
$diff[$l] += $v; // the change starts
$diff[$r + 1] -= $v; // the change stops
}
$result = [];
$running = 0;
for ($i = 0; $i < $n; $i++) { // one sweep
$running += $diff[$i];
$result[] = $running;
}
return $result;
}
$jobs = [[1, 3, 2], [2, 5, 3], [0, 1, 1]];
echo implode(', ', applyUpdates(6, $jobs)) . PHP_EOL; // 1, 3, 5, 5, 3, 3JavaScript
// Apply many "add v to every index from l to r" updates quickly
function applyUpdates(n, updates) {
const diff = new Array(n + 1).fill(0); // one spare box at the end
for (const [l, r, v] of updates) {
diff[l] += v; // the change starts
diff[r + 1] -= v; // the change stops
}
const result = [];
let running = 0;
for (let i = 0; i < n; i++) { // one sweep
running += diff[i];
result.push(running);
}
return result;
}
const jobs = [[1, 3, 2], [2, 5, 3], [0, 1, 1]];
console.log(applyUpdates(6, jobs).join(', ')); // 1, 3, 5, 5, 3, 3Java
import java.util.*;
public class Main {
// Apply many "add v to every index from l to r" updates quickly
static int[] applyUpdates(int n, int[][] updates) {
int[] diff = new int[n + 1]; // one spare box at the end
for (int[] u : updates) {
int l = u[0], r = u[1], v = u[2];
diff[l] += v; // the change starts
diff[r + 1] -= v; // the change stops
}
int[] result = new int[n];
int running = 0;
for (int i = 0; i < n; i++) { // one sweep
running += diff[i];
result[i] = running;
}
return result;
}
public static void main(String[] args) {
int[][] jobs = {{1, 3, 2}, {2, 5, 3}, {0, 1, 1}};
System.out.println(Arrays.toString(applyUpdates(6, jobs))); // [1, 3, 5, 5, 3, 3]
}
}Go
package main
import "fmt"
// applyUpdates applies many "add v to every index from l to r" updates quickly.
func applyUpdates(n int, updates [][3]int) []int {
diff := make([]int, n+1) // one spare box at the end
for _, u := range updates {
l, r, v := u[0], u[1], u[2]
diff[l] += v // the change starts
diff[r+1] -= v // the change stops
}
result := make([]int, n)
running := 0
for i := 0; i < n; i++ { // one sweep
running += diff[i]
result[i] = running
}
return result
}
func main() {
jobs := [][3]int{{1, 3, 2}, {2, 5, 3}, {0, 1, 1}}
fmt.Println(applyUpdates(6, jobs)) // [1 3 5 5 3 3]
}Time: O(n + q) · Extra space: O(n). Each of the q updates costs O(1), then one O(n) sweep finishes everything. The slow way costs O(n × q).
Watch out for
- Forgetting the spare box, so
diff[r + 1]is lost or crashes when r is the last index. - Subtracting at
rinstead ofr + 1, which stops the change one bed too early. - Reading the difference array as if it were the answer. You must do the running-total sweep first.
Quick check
- How many array cells does one range update touch?
- Every cell in the range
- One cell
- Two cells
- What turns the marks into real values?
- Sorting
- A running total sweep
- Reversing
- Difference arrays are the opposite twin of which technique?
- Prefix sums
- Binary search
- Recursion