Answer any range-sum question in O(1) after one O(n) pass.
Use it when the data does not change and you must answer many questions about the total of a range or a rectangle. Signal words: between l and r, many queries, sum of a rectangle, left total equals right total.
Start prefix has one entry, 0.
Step add each value to the running total and append the total. Build a 2D table with one extra row and column of zeros.
Answer places left to right: prefix[right + 1] - prefix[left]. Rectangle: add and subtract the four corners.
It does not fit data that changes between questions, or a question that is not a total.
Cost: O(n) to build, O(1) for each question, O(n) extra space for the list.
In this lesson you answer many range questions on one fixed array. You build a running total once, and then every question costs one subtraction. You also take the same idea to a grid.
You work on the sales dashboard of an online store. The store keeps one number for every minute: the units sold in that minute. Analysts open the dashboard and ask for the total between two moments.
A year has 525,600 minutes, and a busy refresh asks about 200,000 ranges. Adding two numbers takes about a nanosecond.
Your team lead says: The dashboard must answer every range question within a blink. Give me the total of the units between minute l and minute r.
Here is a short test: the units for 7 days are 5, 2, 9, 4, 7, 3 and 8. The total of days 2 to 5 is 9 + 4 + 7 + 3, which is 23.
So the task is this: the numbers never change, the questions come in thousands, and each answer must be fast.
A railway has a marker at every station. The marker shows how many kilometres the line has run from the first station. The first station shows 0.
To find the distance between two stations, you do not measure the track. You read the two markers and subtract. The markers are the prefix list, and the subtraction is the answer to the question.
Like markers on a railway: each station shows the distance so far, and the distance between two stations is one subtraction.
Before you write code, write the markers for the seven days by hand. It shows what the list must hold.
Solve it by hand: Seven days: the prefix list and one range. The hand-solve sheet loads in your browser.
Keep one rule in mind. Each marker is the one before it plus the next day. The list starts with a 0, because the total of no days is 0.
The units are 5, 2, 9, 4, 7, 3 and 8. The question is days 2 to 5.
| Place | Value | Running total | prefix after |
|---|---|---|---|
| start | 0 | [0] | |
| 0 | 5 | 5 | [0, 5] |
| 1 | 2 | 7 | [0, 5, 7] |
| 2 | 9 | 16 | [0, 5, 7, 16] |
| 3 | 4 | 20 | [0, 5, 7, 16, 20] |
| 4 | 7 | 27 | [0, 5, 7, 16, 20, 27] |
| 5 | 3 | 30 | [0, 5, 7, 16, 20, 27, 30] |
| 6 | 8 | 38 | [0, 5, 7, 16, 20, 27, 30, 38] |
Days 2 to 5 end after place 5 and start before place 2. That is prefix[6] - prefix[2] = 30 - 7 = 23. It matches the sum of 9, 4, 7 and 3.
Start with a correct version. For each question, add up the numbers from l to r.
def range_totals(values, queries):
answers = []
for left, right in queries:
total = 0
for index in range(left, right + 1): # add every day in the range
total += values[index]
answers.append(total)
return answersThis is correct. On the test it makes a few additions, which is fine for 7 days.
Now check the real size.
A year has 525,600 minutes. A seeded refresh asks 200,000 ranges. An addition takes 1 nanosecond.
Here is the count from running the code:
So one refresh takes about 35 seconds, and the dashboard is meant to answer at once.
Predict the cost
Q A range of width w costs w additions. What drives the total cost of 200,000 questions?
Answer: B
Each question adds up its own range. The cost is the sum of the widths: 200,000 questions of about 175,787 minutes each.
The first attempt is correct, but every question adds up the same minutes again. Now look at what the questions share.
Look at two questions that start at the same day. Days 0 to 5 and days 0 to 3 share the first four days. Add up days 0 to 3 once, and you can reuse it.
So keep one list of running totals. prefix[i] is the total of the first i values. To get days 2 to 5, take the total of the first 6 days and remove the total of the first 2 days.
The list starts with prefix[0] = 0, so it has one more entry than the values. That zero is what makes a range from day 0 work like every other range.
Here is the same year of questions, counted both ways:
| Method | Additions and subtractions | Time at 1 nanosecond |
|---|---|---|
| Add up each range | 35,157,418,781 | 35 seconds |
| Build the prefix list, subtract per question | 725,600 | 0.7 milliseconds |
The prefix list costs 525,600 additions once, and each of the 200,000 questions costs one subtraction. That is about 48,000 times fewer steps.
Race: Answering n range questions on n values. The operation counter loads in your browser.
At 1,000 values and 1,000 questions, adding up each range costs 327,809 steps and the prefix list costs 2,000. At 10,000 values the counts are 33,159,236 against 20,000.
Each prefix entry is the entry before it plus the next value, and the list starts with a zero.
The units are [4, 1, 6, 3, 8, 2, 7, 5], and the questions are days 1 to 4 and day 3 alone. The player stops at five steps and asks you for a number.
Dry run: Predict each step: eight days, two questions. 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 |
|---|---|---|
| Build, place 1 | total 4 plus the value 1 | 5 |
| Build, place 3 | total 11 plus the value 3 | 14 |
| Build, place 5 | total 22 plus the value 2 | 24 |
| Question 1 to 4 | prefix[5] - prefix[1] = 22 - 4 | 18 |
| Question 3 to 3 | prefix[4] - prefix[3] = 14 - 11 | 3 |
The full list is [0, 4, 5, 11, 14, 22, 24, 31, 36]. A question about one day is prefix[4] - prefix[3], so a range of width 1 needs no special case.
A store also keeps a grid: units sold for each block of a city map. A question now asks for a rectangle of blocks. Adding each block of the rectangle costs its area, so the same trouble comes back.
The grid has a prefix table too. Cell table[i][j] is the total of every block above row i and left of column j. The table has one extra row and one extra column, both zeros, for the same reason as before.
Dry run: A 3 by 4 grid and one rectangle. The step-by-step player loads in your browser.
The run builds the table for a 3 by 4 grid, one cell at a time. Then it answers the rectangle of rows 1 to 2 and columns 1 to 2. The table is shown row by row as one list of 20 cells.
In a 2D table, a cell adds the cell above and the cell to its left, then subtracts the overlap that both include.
Each cell adds the cell above and the cell to its left. Both of them include the cell above-left, so it is counted twice. You subtract it once. A rectangle needs the same care: the big corner, minus the strip above, minus the strip to the left, plus the corner that both strips removed.
Exercise · Predict the output: Three questions, three subtractions. The prefix list has a leading zero. What does this print?
values = [3, 1, 4, 1, 5, 9, 2, 6]
prefix = [0]
for value in values:
prefix.append(prefix[-1] + value)
print(prefix[6] - prefix[2], prefix[4] - prefix[1], prefix[5] - prefix[4])Here is the rule that keeps a prefix list correct. Every line of both templates exists to protect it.
prefix[i] is the total of the first i values, and prefix[0] is 0, so the total of places left to right is prefix[right + 1] - prefix[left].
At the start the list holds only the 0. Each step adds the next value to the running total and appends it. When the build ends, the list is one longer than the values, and every question is a subtraction of two entries.
Use it when the data does not change and you must answer many questions about the total of a range or a rectangle. Signal words: between l and r, many queries, sum of a rectangle, left total equals right total.
Start: prefix has one entry, 0.
Step: add each value to the running total and append the total. Build a 2D table with one extra row and column of zeros.
Answer: places left to right: prefix[right + 1] - prefix[left]. Rectangle: add and subtract the four corners.
It does not fit data that changes between questions, or a question that is not a total.
Cost: O(n) to build, O(1) for each question, O(n) extra space for the list.
def range_sums(values, queries):
# [1] Make a prefix list with a leading zero: prefix[i] is the total of the first i values.
prefix = [0]
# [2] Walk the values once, adding each to the running total.
total = 0
for value in values:
total += value
prefix.append(total)
answers = []
for left, right in queries:
# [3] Answer a question about places left to right as one subtraction.
answers.append(prefix[right + 1] - prefix[left])
# [4] Return the answers.
return answerspublic long[] rangeSums(int[] values, int[][] queries) {
// [1] Make a prefix list with a leading zero: prefix[i] is the total of the first i values.
long[] prefix = new long[values.length + 1];
// [2] Walk the values once, adding each to the running total.
long total = 0;
for (int index = 0; index < values.length; index++) {
total += values[index];
prefix[index + 1] = total;
}
long[] answers = new long[queries.length];
for (int q = 0; q < queries.length; q++) {
int left = queries[q][0];
int right = queries[q][1];
// [3] Answer a question about places left to right as one subtraction.
answers[q] = prefix[right + 1] - prefix[left];
}
// [4] Return the answers.
return answers;
}vector<long long> rangeSums(vector<int>& values, vector<vector<int>>& queries) {
// [1] Make a prefix list with a leading zero: prefix[i] is the total of the first i values.
vector<long long> prefix(values.size() + 1, 0);
// [2] Walk the values once, adding each to the running total.
long long total = 0;
for (int index = 0; index < (int)values.size(); index++) {
total += values[index];
prefix[index + 1] = total;
}
vector<long long> answers;
for (auto& query : queries) {
int left = query[0];
int right = query[1];
// [3] Answer a question about places left to right as one subtraction.
answers.push_back(prefix[right + 1] - prefix[left]);
}
// [4] Return the answers.
return answers;
}function rangeSums(values, queries) {
// [1] Make a prefix list with a leading zero: prefix[i] is the total of the first i values.
const prefix = [0];
// [2] Walk the values once, adding each to the running total.
let total = 0;
for (const value of values) {
total += value;
prefix.push(total);
}
const answers = [];
for (const [left, right] of queries) {
// [3] Answer a question about places left to right as one subtraction.
answers.push(prefix[right + 1] - prefix[left]);
}
// [4] Return the answers.
return answers;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Put it in order: Build once, subtract per question. Arrange the lines into a function that answers every range question with one subtraction.
def range_sums(values, queries):
prefix = [0]
answers = []
for value in values:
prefix.append(prefix[-1] + value)
for left, right in queries:
answers.append(prefix[right + 1] - prefix[left])
return answers
answers.append(prefix[right] - prefix[left])A range total is prefix[right + 1] minus prefix[left]: the end entry sits one place after the last value.
def rectangle_sums(grid, queries):
rows = len(grid)
cols = len(grid[0])
# [1] Make a table one row and one column larger than the grid, filled with zeros.
table = [[0] * (cols + 1) for _ in range(rows + 1)]
# [2] Each table cell is its grid value plus the table above it and to its left, minus the overlap.
for row in range(rows):
for col in range(cols):
table[row + 1][col + 1] = grid[row][col] + table[row][col + 1] + table[row + 1][col] - table[row][col]
answers = []
for top, left, bottom, right in queries:
# [3] A rectangle is the big corner, minus the strip above, minus the strip to the left, plus the overlap.
answers.append(table[bottom + 1][right + 1] - table[top][right + 1] - table[bottom + 1][left] + table[top][left])
# [4] Return the answers.
return answerspublic long[] rectangleSums(int[][] grid, int[][] queries) {
int rows = grid.length;
int cols = grid[0].length;
// [1] Make a table one row and one column larger than the grid, filled with zeros.
long[][] table = new long[rows + 1][cols + 1];
// [2] Each table cell is its grid value plus the table above it and to its left, minus the overlap.
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
table[row + 1][col + 1] = grid[row][col] + table[row][col + 1] + table[row + 1][col] - table[row][col];
}
}
long[] answers = new long[queries.length];
for (int q = 0; q < queries.length; q++) {
int top = queries[q][0];
int left = queries[q][1];
int bottom = queries[q][2];
int right = queries[q][3];
// [3] A rectangle is the big corner, minus the strip above, minus the strip to the left, plus the overlap.
answers[q] = table[bottom + 1][right + 1] - table[top][right + 1] - table[bottom + 1][left] + table[top][left];
}
// [4] Return the answers.
return answers;
}vector<long long> rectangleSums(vector<vector<int>>& grid, vector<vector<int>>& queries) {
int rows = (int)grid.size();
int cols = (int)grid[0].size();
// [1] Make a table one row and one column larger than the grid, filled with zeros.
vector<vector<long long>> table(rows + 1, vector<long long>(cols + 1, 0));
// [2] Each table cell is its grid value plus the table above it and to its left, minus the overlap.
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
table[row + 1][col + 1] = grid[row][col] + table[row][col + 1] + table[row + 1][col] - table[row][col];
}
}
vector<long long> answers;
for (auto& query : queries) {
int top = query[0];
int left = query[1];
int bottom = query[2];
int right = query[3];
// [3] A rectangle is the big corner, minus the strip above, minus the strip to the left, plus the overlap.
answers.push_back(table[bottom + 1][right + 1] - table[top][right + 1] - table[bottom + 1][left] + table[top][left]);
}
// [4] Return the answers.
return answers;
}function rectangleSums(grid, queries) {
const rows = grid.length;
const cols = grid[0].length;
// [1] Make a table one row and one column larger than the grid, filled with zeros.
const table = Array.from({ length: rows + 1 }, () => new Array(cols + 1).fill(0));
// [2] Each table cell is its grid value plus the table above it and to its left, minus the overlap.
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
table[row + 1][col + 1] = grid[row][col] + table[row][col + 1] + table[row + 1][col] - table[row][col];
}
}
const answers = [];
for (const [top, left, bottom, right] of queries) {
// [3] A rectangle is the big corner, minus the strip above, minus the strip to the left, plus the overlap.
answers.push(table[bottom + 1][right + 1] - table[top][right + 1] - table[bottom + 1][left] + table[top][left]);
}
// [4] Return the answers.
return answers;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The table that counts a corner twice. This rectangle-total code fills the prefix table, and its answers come out too big on any grid with more than one row and column. Which line is wrong?
def rectangle_sums(grid, queries):
rows = len(grid)
cols = len(grid[0])
table = [[0] * (cols + 1) for _ in range(rows + 1)]
for row in range(rows):
for col in range(cols):
table[row + 1][col + 1] = grid[row][col] + table[row][col + 1] + table[row + 1][col] + table[row][col]
answers = []
for top, left, bottom, right in queries:
answers.append(table[bottom + 1][right + 1] - table[top][right + 1] - table[bottom + 1][left] + table[top][left])
return answersExercise · Break it: The balance point that counts itself. This code looks for a place where the total to its left equals the total to its right, but it counts the value at the place on the left as well. Find a list where it gives the wrong answer.
def pivot_index(values):
prefix = [0]
for value in values:
prefix.append(prefix[-1] + value)
total = prefix[-1]
for i in range(len(values)):
if prefix[i + 1] == total - prefix[i + 1]:
return i
return -1The 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 a range of one value, on a range from place 0, and on a grid of one cell?
| Situation | Method | Why |
|---|---|---|
| Total of places l to r, many times | One prefix list | O(n) once, O(1) each |
| Total of a rectangle, many times | 2D prefix table | O(rows × cols) once, O(1) each |
| Left total against right total | Prefix list and the grand total | Right total is grand total minus prefix[i] |
| Values change often | A tree, not a prefix list | Each change costs an O(n) rebuild |
A payments app keeps a ledger of 6 entries in units: 4, -1, 3, 2, -2, 6. Your team lead asks where the ledger can be cut so that the left part and the right part have the same total.
Build the prefix list [0, 4, 3, 6, 8, 6, 12]. The grand total is 12, so a cut after place i is balanced when prefix[i + 1] * 2 equals 12, that is, when the prefix is 6.
The prefix is 6 after place 2 and after place 4. Those are the two balanced cuts: 4, -1, 3 against 2, -2, 6, and 4, -1, 3, 2, -2 against 6.
Real data brings edge cases.
For values = [5, 2, 9, 4, 7, 3, 8] and the range 6 to 6, the answer is prefix[7] - prefix[6], which is 38 - 30 = 8. A range of width 1 needs no special case.
For the range 0 to 6, the answer is prefix[7] - prefix[0], which is 38 - 0 = 38. The leading zero is what makes this work with no extra check.
For queries = [], the build still runs and the answer list is empty. If you build the list lazily, make sure an empty questions list costs nothing.
Take 100,000 values of 50,000. The total is 5,000,000,000. A 32-bit integer holds at most 2,147,483,647, so the total wraps to 705,032,704. Use long, long long or a Python integer for the prefix list.
This version makes prefix[i] the total of the first i + 1 values, so the list has n entries. A range left to right is then prefix[right] - prefix[left].
Counterexample: for [5, 2, 9, 4, 7, 3, 8] and the range 2 to 5, the list is [5, 7, 16, 20, 27, 30, 38]. The version returns 30 - 16 = 14, because the value at place 2 was removed. The right answer is 23.
A range that starts at place 0 would need a special case, too. Start the list with a 0 and the problem disappears.
This version keeps the leading zero but forgets that the list is shifted by one. It returns prefix[right] - prefix[left].
Counterexample: for the same list and the range 2 to 5, the prefix list is [0, 5, 7, 16, 20, 27, 30, 38]. The version returns 27 - 7 = 20, so it leaves out the value at place 5. The right answer is 23.
With a leading zero, the end of the range is right + 1.
Without a leading zero, prefix[right] - prefix[left] drops the first value of the range: 14 instead of 23.
This version keeps the prefix list in a 32-bit integer. Each value fits, but the total does not.
Counterexample: 100,000 values of 50,000 add up to 5,000,000,000. A 32-bit integer wraps it to 705,032,704, so every range near the end of the list is wrong.
Use a 64-bit integer for any list whose total can pass about 2,000,000,000.
This version answers a rectangle as the big corner minus the strip above and minus the strip to the left. The corner above-left sits in both strips, so it is removed twice.
Counterexample: for the grid [[3, 1, 4, 2], [2, 6, 1, 5], [7, 2, 8, 3]] and the rectangle of rows 1 to 2 and columns 1 to 2, the version returns 34 - 8 - 12 = 14. The right answer is 34 - 8 - 12 + 3 = 17.
Add the overlap back once.
The dashboard also takes corrections: after a refund, one minute's units change. Every change breaks the prefix list from that place to the end, so the list needs a rebuild.
Take 10,000 corrections, each followed by one question, on 525,600 values. Rebuilding after each correction costs 5,256,000,000 additions. A tree with updates costs about 20 steps for each correction and each question.
Your team lead brings four product changes. Each one asks what to store in the list.
The dashboard needs the total between two days, answered thousands of times from one list. This is LeetCode 303: Range Sum Query - Immutable, and it is the first practice problem.
A map app keeps revenue for each block and asks for the total inside a rectangle. Build the 2D table and read four corners. This is LeetCode 304: Range Sum Query 2D - Immutable.
Find the place where the total to the left equals the total to the right. The right total is the grand total minus the prefix and the value itself. This is LeetCode 724: Find Pivot Index.
Count the ranges whose total is exactly k. A prefix total that appeared before, with a difference of k, marks a range. That needs a hash map of earlier prefixes, and it is taught in the hashing module: Prefix sum with a hash map.
A close relative needs no division: the product of all the other values is a prefix product times a suffix product. See Product of the others without division.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you answer many range-total questions on a fixed array. Then say what it costs, and why the list starts with a zero. 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 build a prefix list once. Prefix of i is the total of the first i values, and prefix of zero is zero, so the list is one longer than the array.
The total of places left to right is prefix of right plus one, minus prefix of left. Each question is one subtraction, so the build is O of n and each question is O of one.
The leading zero makes a range from place zero work like any other range. I use 64-bit totals, and I use a different tool when the values change.
For many range-total questions on data that does not change, I build a prefix list once. I start it with a zero. Each entry is the one before it plus the next value, so entry i is the total of the first i values.
The total of places left to right is prefix of right plus one, minus prefix of left. The zero at the start means a range from place zero needs no special case.
That costs O of n to build and O of one for each question. For half a million values and two hundred thousand questions, that is under a million steps instead of tens of billions of additions.
In two dimensions I keep a table with a border of zeros. Each cell adds the cell above and the cell to the left, and subtracts the overlap. A rectangle is four corners. I use 64-bit totals, and I switch to a tree when the values change.
Checkpoint · The prefix list
Q1/3 For values = [5, 2, 9, 4, 7, 3, 8], what is the prefix list?
Answer: B
prefix[i] is the total of the first i values, and prefix[0] is 0. The list has 8 entries for 7 values.
Q2/3 Why does the prefix list start with a 0?
Answer: C
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 What is the total of places 2 to 5 (both included) for the list [0, 5, 7, 16, 20, 27, 30, 38]?
Answer: C
The range ends after place 5 and starts before place 2: prefix[6] - prefix[2] = 30 - 7 = 23.
Checkpoint · Costs
Q1/3 What does it cost to build the prefix list and then answer q questions?
Answer: B
The build adds each value once. Each question is one subtraction, so the whole job is linear in n and q.
Q2/3 A year has 525,600 values and 200,000 questions. Adding up each range costs 35,157,418,781 additions. What does the prefix list cost?
Answer: C
The build is not free. It adds each of the 525,600 values once, and each question costs one subtraction.
Q3/3 Which question is a poor fit for a prefix list?
Answer: C
A change at place i breaks every entry after it, so the list must be rebuilt. The other three questions use fixed data.
Checkpoint · Mistakes
Q1/4 A version has no leading zero, so prefix[i] is the total of the first i + 1 values. For places 2 to 5 it returns prefix[5] - prefix[2]. What goes wrong?
Answer: B
prefix[2] already includes the value at place 2, so subtracting it removes that value. For the lesson's example the version gives 14, not 23.
Q2/4 100,000 values of 50,000 are added into a 32-bit integer. What happens?
Answer: C
The total is 5,000,000,000. Use a 64-bit integer when a total can pass about 2,000,000,000.
Q3/4 In a 2D prefix table, why is the overlap added back for a rectangle?
Answer: B
table[bottom + 1][right + 1] - table[top][right + 1] - table[bottom + 1][left] removes the shared corner twice, so you add table[top][left] once.
Q4/4 In the 2D build, a cell is its grid value plus the cell above, plus the cell to the left, minus the cell above-left. Why subtract the last one?
Answer: B
The cell above and the cell to the left both cover the area above-left of the current cell, so it is counted twice. Subtract it once.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Sales between two days | Shop | Easy | One prefix list, one subtraction for each question |
| 2 | Balanced split of a ledger | Pay | Easy | Left total against the grand total |
| 3 | Pivot index of a load profile | Observe | Easy | The balance point, with the value itself left out |
The checkpoint of the stretch adds Revenue inside a map rectangle, which uses the 2D table.
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.