Apply many range updates in O(1) each and read the result in one pass.
Use it when many range updates come first and the values are read after all of them. Signal words: add to every place in a range, many updates, how many are active, overlapping windows.
Start a change list of n + 1 zeros.
Step for an update from left to right with an amount, add the amount at left and subtract it at right + 1.
Rebuild one running total over the change list gives every value. For huge coordinates, sort the events and sweep.
It does not fit reads that come between updates, or an update that is not an addition.
Cost: O(1) for each update and O(n) to rebuild, with O(n) extra space.
In this lesson you apply many range updates to an array. You write each update in two places, and one pass at the end turns the notes into the final array. It is the mirror image of a prefix sum.
You work on the support desk of an online store. The store plans its support shifts a year ahead. Each shift covers a range of minutes, from the first minute to the last, and one more agent is online for all of them.
A year has 525,600 minutes, and the plan holds about 200,000 shifts. Adding one to a minute takes about a nanosecond.
Your team lead says: After the plan is final, I need the number of agents online in every minute of the year.
Here is a short test: 8 hours, and three shifts that cover hours 1 to 4, hours 3 to 6 and hour 2 alone. The agents online in hours 0 to 7 are 0, 1, 2, 2, 2, 1, 1 and 0.
So the task is this: apply every shift to the plan, then read every minute once.
A train runs through eight stations. A group of passengers boards at one station and leaves at a later one. The conductor does not update the count at every station between the two.
The conductor writes two notes: plus one at the station where the group boards, and minus one at the station where it leaves. To know how many are on board at a station, the conductor adds up all the notes up to it.
Like passengers on a train: write plus one where a group boards and minus one where it leaves, then add up the notes.
Before you write code, record the three shifts by hand. Write only the notes, not the counts.
Solve it by hand: Eight hours, three shifts. The hand-solve sheet loads in your browser.
Keep one rule in mind. A shift that covers hours 1 to 4 adds one at hour 1 and takes one away at hour 5, the hour after its last one.
The plan has 8 hours. The shifts are hours 1 to 4, hours 3 to 6 and hour 2.
| Shift | Notes written | Change list after |
|---|---|---|
| start | [0, 0, 0, 0, 0, 0, 0, 0, 0] | |
| hours 1 to 4 | +1 at 1, -1 at 5 | [0, 1, 0, 0, 0, -1, 0, 0, 0] |
| hours 3 to 6 | +1 at 3, -1 at 7 | [0, 1, 0, 1, 0, -1, 0, -1, 0] |
| hour 2 | +1 at 2, -1 at 3 | [0, 1, 1, 0, 0, -1, 0, -1, 0] |
Now add the notes up from the left. The running totals are 0, 1, 2, 2, 2, 1, 1 and 0, which is the number of agents online in each hour.
Start with a correct version. For each shift, add one to every minute it covers.
def apply_shifts(size, shifts):
online = [0] * size
for first, last in shifts:
for minute in range(first, last + 1): # touch every minute of the shift
online[minute] += 1
return onlineThis is correct. On the test it makes 9 increments, which is fine for 8 hours.
Now check the real size.
A year has 525,600 minutes. A seeded plan has 200,000 shifts. An increment takes 1 nanosecond.
Here is the count from running the code:
So one planning run takes about 35 seconds, and the planners rerun it all day.
Predict the cost
Q A shift of width w costs w increments. What drives the total cost of 200,000 shifts?
Answer: B
Each shift touches every minute it covers. The cost is the sum of the widths: 35,094,342,802 increments for 200,000 shifts.
The first attempt is correct, but it touches the same minutes again and again. Now look at what a shift changes.
Look at the hand trace again. A shift changes the count in only two places: where it starts, and right after it ends. Inside the shift the count stays the same as the minute before.
So do not touch the minutes. Keep a change list. change[i] says how much the count at place i differs from the count at place i - 1. A shift writes +1 at its first place and -1 right after its last place.
The change list has one more entry than the plan. A shift that ends at the last minute writes its -1 at place n, so that place must exist.
When all the notes are written, walk the change list once with a running total. The total at each place is the count at that place. This is a prefix sum of the change list.
Exercise · Put it in order: From notes to values. Arrange the lines into a function that turns a change list into the values it describes, with one running total.
def changes_to_values(change):
result = []
running = 0
for c in change:
running += c
result.append(running)
return result
result.append(c)Here is the same year, counted both ways:
| Method | Increments or steps | Time at 1 nanosecond |
|---|---|---|
| Add to every minute of each shift | 35,094,342,802 | 35 seconds |
| Two writes per shift, then one pass | 925,600 | 0.9 milliseconds |
Two writes for 200,000 shifts and one pass over 525,600 minutes make 925,600 steps. That is about 38,000 times fewer.
Race: Applying n range updates to n places. The operation counter loads in your browser.
At 1,000 places and 1,000 updates, adding to every place costs 340,733 increments and the change list costs 3,000 steps. At 10,000 places the counts are 33,174,887 against 30,000.
A shift changes the count in two places only: plus one where it starts, and minus one right after it ends.
The plan has 9 places and three signed updates. They add 2 to places 0 to 3, add -1 to places 2 to 5, and add 3 to places 4 to 8. The player stops at five steps and asks you for a number.
Dry run: Predict each step: nine places, three updates. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Step | What happens | Value |
|---|---|---|
| Write the last update | the 3 is taken away right after place 8 | place 9 |
| Place 2 | running total 2, change -1 | 1 |
| Place 4 | running total 1, change +1 | 2 |
| Place 6 | running total 2, change +1 | 3 |
| Place 8 | running total 3, change 0 | 3 |
The change list is [2, 0, -1, 0, 1, 0, 1, 0, 0, -3], and the final array is [2, 2, 1, 1, 2, 2, 3, 3, 3].
Exercise · Predict the output: What do the notes look like?. The plan has 6 places and three updates, written as left, right and amount. This code writes only the notes. What does it print: the whole change list?
size = 6
change = [0] * (size + 1)
for left, right, amount in [(1, 3, 2), (2, 5, 1), (0, 1, 4)]:
change[left] += amount
change[right + 1] -= amount
print(*change)Sometimes the places are moments in time, and the times reach 10^9. An array with a place for every second would hold a billion entries, and nearly all of them would be empty.
Keep only the places where something happens. Each window becomes two events: a +1 at its start and a -1 at its end. Sort the events by time. Then sweep through them with a running count.
Dry run: Four windows swept by their events. The step-by-step player loads in your browser.
The run sweeps four time windows. The highest running count, 3, is reached when the windows 1 to 5, 3 to 8 and 4 to 6 are all running.
For huge times, turn each window into a plus one at its start and a minus one at its end, sort, and sweep.
Here is the rule that keeps a difference array correct. Every line of both templates exists to protect it.
change[i] is the difference between place i and place i - 1, so the running total up to place i is its value.
At the start every note is 0, and the array is all 0. An update adds the amount at its first place and takes it away right after its last place. The notes before place i then add up to exactly the updates that cover place i.
Use it when many range updates come first and the values are read after all of them. Signal words: add to every place in a range, many updates, how many are active, overlapping windows.
Start: a change list of n + 1 zeros.
Step: for an update from left to right with an amount, add the amount at left and subtract it at right + 1.
Rebuild: one running total over the change list gives every value. For huge coordinates, sort the events and sweep.
It does not fit reads that come between updates, or an update that is not an addition.
Cost: O(1) for each update and O(n) to rebuild, with O(n) extra space.
def range_updates(size, updates):
# [1] Make a change list one longer than the array, filled with zeros.
change = [0] * (size + 1)
# [2] Record each update in two places: add it where it starts and take it away right after it ends.
for left, right, amount in updates:
change[left] += amount
change[right + 1] -= amount
# [3] Walk the change list with a running total: the total at each place is the result there.
result = []
running = 0
for index in range(size):
running += change[index]
result.append(running)
# [4] Return the array after all updates.
return resultpublic long[] rangeUpdates(int size, int[][] updates) {
// [1] Make a change list one longer than the array, filled with zeros.
long[] change = new long[size + 1];
// [2] Record each update in two places: add it where it starts and take it away right after it ends.
for (int[] update : updates) {
change[update[0]] += update[2];
change[update[1] + 1] -= update[2];
}
// [3] Walk the change list with a running total: the total at each place is the result there.
long[] result = new long[size];
long running = 0;
for (int index = 0; index < size; index++) {
running += change[index];
result[index] = running;
}
// [4] Return the array after all updates.
return result;
}vector<long long> rangeUpdates(int size, vector<vector<int>>& updates) {
// [1] Make a change list one longer than the array, filled with zeros.
vector<long long> change(size + 1, 0);
// [2] Record each update in two places: add it where it starts and take it away right after it ends.
for (auto& update : updates) {
change[update[0]] += update[2];
change[update[1] + 1] -= update[2];
}
// [3] Walk the change list with a running total: the total at each place is the result there.
vector<long long> result;
long long running = 0;
for (int index = 0; index < size; index++) {
running += change[index];
result.push_back(running);
}
// [4] Return the array after all updates.
return result;
}function rangeUpdates(size, updates) {
// [1] Make a change list one longer than the array, filled with zeros.
const change = new Array(size + 1).fill(0);
// [2] Record each update in two places: add it where it starts and take it away right after it ends.
for (const [left, right, amount] of updates) {
change[left] += amount;
change[right + 1] -= amount;
}
// [3] Walk the change list with a running total: the total at each place is the result there.
const result = [];
let running = 0;
for (let index = 0; index < size; index++) {
running += change[index];
result.push(running);
}
// [4] Return the array after all updates.
return result;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The shift that cancels another. Two shifts begin in the same hour, yet the plan counts only one of them. Which line is wrong?
def range_updates(size, updates):
change = [0] * (size + 1)
for left, right, amount in updates:
change[left] = amount
change[right + 1] -= amount
result = []
running = 0
for index in range(size):
running += change[index]
result.append(running)
return resultAn update from left to right writes plus the amount at left, and minus the amount at right plus one.
def max_overlap(intervals):
# [1] Turn each window into two events: +1 at its start and -1 at its end.
events = []
for start, end in intervals:
events.append((start, 1))
events.append((end, -1))
# [2] Sort the events by time; at the same time an end comes before a start, because the windows are half open.
events.sort()
# [3] Sweep through the events with a running count, and keep the highest count seen.
running = 0
best = 0
for time, step in events:
running += step
best = max(best, running)
# [4] Return the highest count.
return bestpublic int maxOverlap(int[][] intervals) {
// [1] Turn each window into two events: +1 at its start and -1 at its end.
long[] events = new long[intervals.length * 2];
for (int i = 0; i < intervals.length; i++) {
events[2 * i] = (long) intervals[i][0] * 2 + 1;
events[2 * i + 1] = (long) intervals[i][1] * 2;
}
// [2] Sort the events by time; at the same time an end comes before a start, because the windows are half open.
java.util.Arrays.sort(events);
// [3] Sweep through the events with a running count, and keep the highest count seen.
int running = 0;
int best = 0;
for (long event : events) {
running += (event % 2 == 1) ? 1 : -1;
best = Math.max(best, running);
}
// [4] Return the highest count.
return best;
}int maxOverlap(vector<vector<int>>& intervals) {
// [1] Turn each window into two events: +1 at its start and -1 at its end.
vector<pair<int, int>> events;
for (auto& window : intervals) {
events.push_back({window[0], 1});
events.push_back({window[1], -1});
}
// [2] Sort the events by time; at the same time an end comes before a start, because the windows are half open.
sort(events.begin(), events.end());
// [3] Sweep through the events with a running count, and keep the highest count seen.
int running = 0;
int best = 0;
for (auto& event : events) {
running += event.second;
best = max(best, running);
}
// [4] Return the highest count.
return best;
}function maxOverlap(intervals) {
// [1] Turn each window into two events: +1 at its start and -1 at its end.
const events = [];
for (const [start, end] of intervals) {
events.push([start, 1]);
events.push([end, -1]);
}
// [2] Sort the events by time; at the same time an end comes before a start, because the windows are half open.
events.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
// [3] Sweep through the events with a running count, and keep the highest count seen.
let running = 0;
let best = 0;
for (const [time, step] of events) {
running += step;
best = Math.max(best, running);
}
// [4] Return the highest count.
return best;
}Rebuild the template: put its lines back in order. Loads in your browser.
The two templates cover two shapes of question. You can pick before you write any code.
Then check the ends. What do the templates do on an update to the last place, on no updates, and on windows that touch?
| Situation | Method | Why |
|---|---|---|
| Many range updates, then read all | Change list and one pass | 2 writes per update, O(n) once |
| How many windows are active, small places | Change list of +1 and -1 | Same pass, same cost |
| How many windows are active, huge times | Events and a sweep | Cost depends on windows, not on time |
| Reads between updates | A tree, not a difference array | Each read costs an O(n) rebuild |
An ad app has a rate card of 6 slots, each priced at 10 units. Three adjustments arrive: add 5 to slots 0 to 2, add -3 to slots 1 to 4, and add 2 to slots 3 to 5.
Write the notes: the change list is [5, -3, 0, -3, 0, 3, -2]. The running totals are 5, 2, 2, -1, -1 and 2. Add the base price of 10 to each.
The final rate card is 15, 12, 12, 9, 9 and 12, after 6 writes and one pass.
Real data brings edge cases.
For size = 5 and the update [2, 4, 1], the take-away goes to place 5. The change list has 6 entries, so place 5 exists, and the result is [0, 0, 1, 1, 1].
For updates = [], the change list stays all 0, and the running total gives [0, 0, 0, 0] for size 4.
For intervals = [[1, 3], [3, 5]], the windows are half open, so the first one ends at time 3 and the second starts at time 3. They are never running together. The answer is 1, because an end sorts before a start at the same time.
Take 100,000 copies of the update [0, 9, 50000]. The total is 5,000,000,000, which a 32-bit integer wraps to 705,032,704. Use a 64-bit change list.
This version writes the take-away at right instead of right + 1.
Counterexample: for size = 8 and the update [1, 4, 1], the version returns [0, 1, 1, 1, 0, 0, 0, 0]. Place 4 is covered, but the take-away already happened there. The right answer is [0, 1, 1, 1, 1, 0, 0, 0].
The note goes right after the range, at right + 1.
This version makes the change list the same length as the array. An update that ends at the last place writes to place n.
Counterexample: size = 5 and [2, 4, 1]. The write goes to place 5 of a list with places 0 to 4, so the version stops with an index error.
Make the list one entry longer than the array.
Returning the change list without a running total gives differences, not counts: the update 1 to 4 returns a minus one at place 5.
This version returns the change list itself and skips the running total.
Counterexample: for size = 8 and [1, 4, 1], its first 8 entries are [0, 1, 0, 0, 0, -1, 0, 0]. The right answer is [0, 1, 1, 1, 1, 0, 0, 0].
The change list holds differences. A running total turns them into values.
This version sorts events so that a start comes before an end at the same time. Half-open windows that touch would then overlap.
Counterexample: the windows [1, 3] and [3, 5]. The version returns 2, because it counts the start at time 3 before the end at time 3. The right answer is 1.
Sort by time, and put the end first.
The support desk now changes the plan all day and reads the number of agents online right after each change. Each read needs the running total, so each read needs a rebuild.
Take 10,000 changes, each followed by one read, on 525,600 places. The rebuilds cost 5,256,000,000 steps. A tree with updates costs about 20 steps for each change and each read.
Your team lead brings four product changes. Each one asks what a note means.
A shuttle has a fixed number of seats. Each booking adds riders between two stops, and you must check that the load never goes above the seats. Write +riders at the first stop and -riders at the stop where they leave, and sweep. This is LeetCode 1094: Car Pooling.
An array starts at 0, and each update adds an amount to a range. This is LeetCode 370: Range Addition, and the rate card problem of this lesson adds a base price to it.
Each booking reserves seats on a run of flights, and you return the seats booked on each flight. This is LeetCode 1109: Corporate Flight Bookings.
The notes also tell you how many range edits you need. A profile is flat when every note between neighbours is 0, and each edit moves at most two notes by one. That is the idea of the hard problem of this lesson.
On a grid, the same idea uses four notes for each rectangle. That is LeetCode 2536: Increment Submatrices by One.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you apply many range updates to an array. Then say what each update costs, and how you get the final array. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
I do not touch the places. For each update from left to right, I add the amount at left in a change list, and take it away at right plus one.
The change list has one extra entry, so an update at the last place is safe. Each update costs two writes, which is O of one.
At the end one running total over the change list gives the final array. That pass is O of n, and it is the reverse of a prefix sum.
For many range updates, I do not add to every place. I keep a change list, one entry longer than the array. For an update from left to right, I add the amount at left, and take it away at right plus one.
Each update is two writes, whatever the length of the range. When all updates are in, I walk the change list with a running total. The total at each place is the value there.
That costs O of one for each update and O of n once. For two hundred thousand updates on half a million places, that is under a million steps instead of tens of billions of increments.
If the coordinates are huge, I use events instead: plus one at each start, minus one at each end, sorted, and swept with a running count. I put an end before a start at the same time. I use 64-bit totals, and I switch to a tree when reads come between updates.
Checkpoint · Range sums
Q1/3 For values = [5, 2, 9, 4, 7, 3, 8], the prefix list is [0, 5, 7, 16, 20, 27, 30, 38]. What is the total of places 2 to 5?
Answer: C
The range ends after place 5 and starts before place 2: prefix[6] - prefix[2] = 30 - 7 = 23.
Q2/3 Why does the prefix list start with a 0?
Answer: B
The total of no values is 0. With that entry, prefix[right + 1] - prefix[left] works for left = 0 with no special case.
Q3/3 In a 2D prefix table, a rectangle is the big corner minus the strip above, minus the strip to the left. What is the last step?
Answer: B
The corner above-left sits inside both strips, so it was removed twice. You add it back once.
Checkpoint · Range updates
Q1/4 An update adds 4 to places 2 to 6 of an array with 10 places. Which two notes go in the change list?
Answer: B
The take-away goes right after the range, at right + 1 = 7. That is why place 6 still holds the 4.
Q2/4 Why is the change list one entry longer than the array?
Answer: C
With n places, the last place is n - 1, so the take-away goes to place n. Without that entry the write would fall outside the list.
Q3/4 How do you get the final array from the change list?
Answer: C
The change list holds differences between neighbours. A running total, which is a prefix sum, turns them back into values.
Q4/4 100,000 range updates on 525,600 places. Adding to every place costs billions of increments. What does the change list cost?
Answer: B
Each update is two writes whatever its length, and the rebuild is one pass of O(n).
Checkpoint · Events and limits
Q1/3 The windows 1 to 3 and 3 to 5 are half open. How many are running together at the most?
Answer: B
In a half-open window the end time is not part of it. Sort an end before a start at the same time, and the count never reaches 2.
Q2/3 Reads come between updates: after each change you must read one value at once. Which tool fits?
Answer: B
Each read of a difference array needs a rebuild of O(n). A tree answers both in O(log n).
Q3/3 A prefix list or a change list can hold totals past 2,000,000,000. Which type do you use?
Answer: B
100,000 values of 50,000 add up to 5,000,000,000, which wraps in a 32-bit integer.
Ten questions on this lesson and the prefix sums of the one before. Pass with 80% or more to be sure the ideas have landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Busiest year of active accounts | Bank | Easy | Notes by year, one running total |
| 2 | Paint the rate card ranges | Ads | Medium | Signed updates on a base array |
| 3 | Overlapping promotions count | Feed | Medium | A sweep over events with huge times |
| 4 | Fewest edits to flatten a profile | Platform | Hard | Reading the edits from the notes |
The checkpoint of the stretch adds Revenue inside a map rectangle and Flight seats booked.
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.