Range updates with a difference array
1 Many updates, one array at the end
Some problems give us an array and a long list of updates. Each update says: add v to every value from index l to index r. After all the updates, we need the final array.
Our running example has six values, all 0, and three updates:
| Update | l | r | v |
|---|---|---|---|
| 1 | 1 | 3 | +5 |
| 2 | 2 | 5 | +3 |
| 3 | 0 | 1 | +2 |
The direct way loops over each range and adds v to every value in it:
for each update (l, r, v)
for i from l to r
nums[i] = nums[i] + v
One update can cover the whole array, so it costs up to n steps. With q updates, that is up to n × q steps. At n = q = 10⁵, that is around 10¹⁰ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).
A difference array does each update in two steps, however long its range is. Then one pass at the end builds the whole array.
2 Two marks per update
We do not write v into every place in the range. We write two marks in a new array, diff:
- +v at l, where the range starts.
- −v at r + 1, the first place after the range ends.
Then we walk along diff once and keep a running sum. The running sum at index i is the final value at index i.
Here is update 1 alone, which adds 5 to indexes 1 to 3:
The +5 at index 1 switches the change on. From there, every running sum carries the 5. The −5 at index 4 switches it off again. So indexes 1, 2 and 3 get the 5, and nothing outside the range does.
diff needs n + 1 places, one more than the array. When a range ends at the last index, n − 1, its −v goes at index n. The walk never reads that place, but the write needs somewhere to go.
3 Why the marks work
The name comes from what diff holds. The difference at index i is nums[i] − nums[i − 1]: how far a value rises or falls from its left neighbour. Index 0 has no left neighbour, so its difference is nums[0] itself.
Adding up the differences from the start gives back the array, because each one says how far to move from the value before it. Here is that with nums = [4, 1, 6, 2, 0, 3], before and after adding 5 to indexes 1 to 3:
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| nums | 4 | 1 | 6 | 2 | 0 | 3 |
| Differences | 4 | −3 | 5 | −4 | −2 | 3 |
| nums after +5 on [1, 3] | 4 | 6 | 11 | 7 | 0 | 3 |
| Differences after | 4 | 2 | 5 | −4 | −7 | 3 |
The running sums of 4, −3, 5, −4, −2, 3 are 4, 1, 6, 2, 0, 3, which is nums. After the update, only two differences changed:
- Inside the range, a value and its left neighbour both rose by 5. Their difference stayed the same.
- At l = 1, nums[1] rose by 5 but nums[0] did not. The difference rose by 5.
- At r + 1 = 4, nums[3] rose by 5 but nums[4] did not. The difference fell by 5.
So a range update changes the differences in exactly two places. We keep the differences instead of the values, and we turn them back into values once, at the end.
4 The worked example
Back to our six zeros. All their differences are 0, so diff starts as seven zeros. Each update adds its two marks:
Update 3 shows that marks add up. Index 2 already held +3 from update 2, and update 3's −2 lands there too. We always add to a place, never overwrite it.
Now one walk turns diff into the answer. running starts at 0, and at each index we add diff[i] to it:
| i | diff[i] | running | result[i] |
|---|---|---|---|
| 0 | 2 | 2 | 2 |
| 1 | 5 | 7 | 7 |
| 2 | 1 | 8 | 8 |
| 3 | 0 | 8 | 8 |
| 4 | −5 | 3 | 3 |
| 5 | 0 | 3 | 3 |
The table shows each update's marks at work. The +5 from index 1 stays in running until the −5 at index 4 takes it out. The −3 at index 6 is never read, because the walk stops at index 5. The direct way gives the same [2, 7, 8, 8, 3, 3].
5 The code
The function takes the starting values nums and the updates, each as [l, r, v]. It adds each index's total change to its starting value. For counts that start at zero, nums is all zeros.
On our six zeros, it returns [2, 7, 8, 8, 3, 3]. On nums = [4, 1, 6, 2, 0, 3] with the same updates, it returns [6, 8, 14, 10, 3, 6]: each starting value plus its total change.
6 What it costs
Each update writes two places, so all q updates take about 2q steps. The walk takes n steps. In all, that is O(n + q) time. At n = q = 10⁵, that is around 2 × 10⁵ steps, against 10¹⁰ for the direct way.
diff takes n + 1 extra places, so the extra space is O(n).
7 Mistakes and edge cases
- No extra place. With
diffof size n, update 2 in our example writesdiff[6], past the end. That is a Runtime Error, or in some languages a silent write into other memory. Makediffn + 1 long. - Positions numbered from 1. Many problems number positions 1 to n, such as flights 1 to n. A booking for flights 1 to 2 means indexes 0 and 1. Subtract 1 from l and r before writing the marks.
- Ends that are not included. Some ranges run from l up to, but not including, r. A passenger who gets off at stop 5 is not in the car at stop 5. The range then ends at r − 1, so the −v goes at r itself.
- Overflow. Many updates can pile onto one index. With 10⁵ updates of 10⁹ each, one value reaches 10¹⁴, far past the
intlimit of about 2 × 10⁹. Sodiff,runningand the result uselong long. - Reading values between updates.
diffgives the array only after the walk. If the problem asks for a value after every update, the walk would run each time, n steps per question. The Range Queries lessons cover structures for that.
8 When to use it
A difference array fits when many updates each change a whole range, and the question needs the array only after all of them. It shows up in a few shapes:
- Totals per position. Each booking adds seats to a range of flights, and we want each flight's total.
- Load over time. Each trip has passengers on board from one stop to another. The walk checks each running sum against the car's capacity.
- Shifts on ranges of a string. Each update shifts a range of letters forward or back. The total shift at each letter, taken mod 26, gives the new letter.
- Intervals covering points. Each interval writes +1 where it starts and −1 just after it ends. The running sum counts how many intervals cover each point, and its largest value is the most that overlap.
diff has its extra place and whether the ends are included.Practice it
- Corporate Flight BookingsMedium
- Car PoolingMedium
- Shifting Letters IIMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.