Pattern #08
Difference Array
RecommendedRange updates in O(1); rebuild the array with a prefix pass.
When to use
Many updates add a value to an entire range [L, R], then you need the final array or range queries after updates.
Recognition cues
- Add val to every index in [L, R] (many times)
- Corporate flight bookings / range addition
- Difference array then prefix restore
Common pitfalls
- Off-by-one on R+1 when marking the end of a range
- Forgetting the final prefix pass before reading values
- Using this when you need true segment-tree style mixed queries mid-stream
90-second recognition drill
Which pattern fits best?
- Add val to every index in [L, R] (many times)
- Corporate flight bookings / range addition
- Difference array then prefix restore
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
diff starts at zeros
How to think about it
Instead of updating every cell in a range, write the start and the undo on a diff array. After all updates, a single prefix sum rebuilds the values. Each update is O(1); rebuild is O(n). A range that still applies at its last index undoes at R + 1. A trip that has already ended undoes at that stop itself.
Template shapes
| Shape | Core move | Example |
|---|---|---|
| Range add | diff[L] += v and diff[R + 1] -= v, then one prefix. The range is never walked |
LC 370 |
| Timeline load | diff[from] += passengers and diff[to] -= passengers. The prefix is the load between stops. The drop is at to because the trip has ended |
LC 1094 |
| 1-indexed bookings | diff[first - 1] += seats, and diff[last] -= seats when last < n. The prefix is seats per flight |
LC 1109 |
| Coverage | Each range adds 1: diff[start] += 1 and diff[end + 1] -= 1. Every integer from left to right needs a prefix of at least 1 |
LC 1893 |
| Sparse colors | A map stores +color at start and -color at end. On [prev, cur) the prefix is the mixed color. A zero color emits no segment |
LC 1943 |
| Letter shifts | Range adds of +1 or -1. The prefix at i is the net shift. The new letter is (s[i] - 'a' + shift) mod 26 |
LC 2381 |
Complexity baseline
O(1) per range update, O(n) to materialize. Space O(n) for the diff array. LC 1943 stores only the changed keys.
From template to problem
- Decide where the undo lands. Still applied at
Rmeans undo atR + 1(LC 370). Already finished attomeans undo atto(LC 1094). - Shift 1-indexed endpoints before writing the diff (LC 1109).
- Apply every update, then one prefix. A cell read before that prefix is still a delta.
- When coordinates are sparse, store the deltas in a sorted map and emit a segment only while the running color is non-zero (LC 1943).
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
/** Difference array template: range add then prefix rebuild. */
export function applyRangeUpdates(n: number, updates: number[][]): number[] {
const diff = new Array(n + 1).fill(0);
for (const [l, r, val] of updates) {
diff[l!]! += val!;
if (r! + 1 < diff.length) diff[r! + 1]! -= val!;
}
const out = new Array<number>(n);
let run = 0;
for (let i = 0; i < n; i++) {
run += diff[i]!;
out[i] = run;
}
return out;
}
/** Difference array template: range add then prefix rebuild. */
export function applyRangeUpdates(n: number, updates: number[][]): number[] {
const diff = new Array(n + 1).fill(0);
for (const [l, r, val] of updates) {
diff[l!]! += val!;
if (r! + 1 < diff.length) diff[r! + 1]! -= val!;
}
const out = new Array<number>(n);
let run = 0;
for (let i = 0; i < n; i++) {
run += diff[i]!;
out[i] = run;
}
return out;
}
- 1#370 Range AdditionGuidemedium
- 2#1094 Car PoolingGuidemedium
- 3#1109 Corporate Flight BookingsGuidemedium
- 4#1893 Check if All the Integers in a Range Are CoveredGuideeasy
- 5#1943 Describe the PaintingGuidemedium
- 6#2381 Shifting Letters IIGuidemedium