Range updates with a difference array

Video lessonComing soon

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:

Updatelrv
113+5
225+3
301+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:

00510203−540506
diff: +5 at l = 1, −5 at r + 1 = 4
005152530405
Running sums: 5 at indexes 1 to 3 only

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:

Index012345
nums416203
Differences4−35−4−23
nums after +5 on [1, 3]4611703
Differences after425−4−73

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:

Writing the marks
00010203040506
Start: diff has n + 1 = 7 places, all 0

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:

The running sum
20511203−5405−36i
diff
2012345
running = 0 + 2 = 2, so result[0] = 2
idiff[i]runningresult[i]
0222
1577
2188
3088
4−533
5033

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.

Direct, n × q10¹⁰Difference array, n + q2 × 10⁵about 1 second
Steps at n = q = 10⁵, on a scale where each mark is ten times the last

diff takes n + 1 extra places, so the extra space is O(n).

7 Mistakes and edge cases

  • No extra place. With diff of size n, update 2 in our example writes diff[6], past the end. That is a Runtime Error, or in some languages a silent write into other memory. Make diff n + 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 int limit of about 2 × 10⁹. So diff, running and the result use long long.
  • Reading values between updates. diff gives 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.
Before coding, write the two marks for the update that ends at the last index. That one shows whether diff has its extra place and whether the ends are included.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.