Answer any range-sum question in O(1) after one O(n) pass.
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].
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;
}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;
}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].
This version keeps the leading zero but forgets that the list is shifted by one. It returns prefix[right] - prefix[left].
This version keeps the prefix list in a 32-bit integer. Each value fits, but the total does not.
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.
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.
systemdesignmastery.dev/dsa/cheatsheets/prefix-sums