Full answer
Problem
Part 1: given nums, answer many queries query(left, right) returning sum(nums[left:right + 1]).
Part 2: given a grid, answer query(r1, c1, r2, c2) returning the sum of the rectangle with those corners (inclusive).
Example: nums = [3, -1, 4, 1, 5, 9], query(2, 4) is 4 + 1 + 5 = 10.
Constraints: up to 10^5 values and 10^5 queries; the data does not change between queries.
Brute force
Sum the range on every query: O(n) per query, O(n x q) total, which is 10^10 for the limits above.
Optimal approach
1D. prefix[0] = 0, prefix[i + 1] = prefix[i] + nums[i]. Then sum(l..r) = prefix[r + 1] - prefix[l]. Like a running total of marks: the marks scored between test 3 and test 5 equal the total after test 5 minus the total before test 3.
2D. Use a grid p with an extra zero row and column:
p[r + 1][c + 1] = grid[r][c] + p[r][c + 1] + p[r + 1][c] - p[r][c].
A query subtracts the strip above and the strip to the left, then adds back the corner that was subtracted twice:
p[r2 + 1][c2 + 1] - p[r1][c2 + 1] - p[r2 + 1][c1] + p[r1][c1].
Why it works
Addition is associative, so a range sum equals the difference of two prefix sums. In 2D, inclusion and exclusion removes the unwanted areas exactly once. The extra leading zero row and column remove special cases for ranges starting at index 0.
Complexity
1D: O(n) build, O(1) per query, O(n) space. 2D: O(R x C) build, O(1) per query, O(R x C) space.
Code
class RangeSum:
"""O(1) sum of nums[left..right] after O(n) preprocessing."""
def __init__(self, nums):
self.prefix = [0]
for x in nums:
self.prefix.append(self.prefix[-1] + x) # prefix[i] = sum(nums[:i])
def query(self, left, right):
return self.prefix[right + 1] - self.prefix[left]
class RangeSum2D:
"""O(1) sum of a sub-rectangle of a grid after O(rows * cols) preprocessing."""
def __init__(self, grid):
rows, cols = len(grid), len(grid[0]) if grid else 0
self.p = [[0] * (cols + 1) for _ in range(rows + 1)]
for r in range(rows):
for c in range(cols):
self.p[r + 1][c + 1] = (grid[r][c] + self.p[r][c + 1]
+ self.p[r + 1][c] - self.p[r][c])
def query(self, r1, c1, r2, c2):
p = self.p
return p[r2 + 1][c2 + 1] - p[r1][c2 + 1] - p[r2 + 1][c1] + p[r1][c1]
if __name__ == "__main__":
rs = RangeSum([3, -1, 4, 1, 5, 9])
assert rs.query(0, 5) == 21
assert rs.query(2, 4) == 10
assert rs.query(1, 1) == -1
g = [[3, 0, 1, 4],
[5, 6, 3, 2],
[1, 2, 0, 1]]
rs2 = RangeSum2D(g)
assert rs2.query(0, 0, 2, 3) == 28
assert rs2.query(1, 1, 2, 2) == 11
assert rs2.query(2, 3, 2, 3) == 1
assert RangeSum([]).prefix == [0]
print("all tests passed")Save as a09_range_sum.py and run python3 a09_range_sum.py. It prints all tests passed (Python 3.13.5).
Edge cases
A range of one element. A range starting at index 0 (handled by prefix[0] = 0). Negative values (fine). Empty input. If the data changes between queries, prefix sums need O(n) per update; use a Fenwick tree or segment tree for O(log n) updates and queries.
Pattern
Prefix sums: precompute cumulative totals so a range becomes a difference of two values. It underlies subarray sum equals k, equilibrium index and difference arrays for range updates.
class RangeSum:
"""O(1) sum of nums[left..right] after O(n) preprocessing."""
def __init__(self, nums):
self.prefix = [0]
for x in nums:
self.prefix.append(self.prefix[-1] + x) # prefix[i] = sum(nums[:i])
def query(self, left, right):
return self.prefix[right + 1] - self.prefix[left]
class RangeSum2D:
"""O(1) sum of a sub-rectangle of a grid after O(rows * cols) preprocessing."""
def __init__(self, grid):
rows, cols = len(grid), len(grid[0]) if grid else 0
self.p = [[0] * (cols + 1) for _ in range(rows + 1)]
for r in range(rows):
for c in range(cols):
self.p[r + 1][c + 1] = (grid[r][c] + self.p[r][c + 1]
+ self.p[r + 1][c] - self.p[r][c])
def query(self, r1, c1, r2, c2):
p = self.p
return p[r2 + 1][c2 + 1] - p[r1][c2 + 1] - p[r2 + 1][c1] + p[r1][c1]
if __name__ == "__main__":
rs = RangeSum([3, -1, 4, 1, 5, 9])
assert rs.query(0, 5) == 21
assert rs.query(2, 4) == 10
assert rs.query(1, 1) == -1
g = [[3, 0, 1, 4],
[5, 6, 3, 2],
[1, 2, 0, 1]]
rs2 = RangeSum2D(g)
assert rs2.query(0, 0, 2, 3) == 28
assert rs2.query(1, 1, 2, 2) == 11
assert rs2.query(2, 3, 2, 3) == 1
assert RangeSum([]).prefix == [0]
print("all tests passed")Classes for 1D and 2D prefix sums with a leading zero row and column to avoid edge cases.
Complexity
Time: Build O(n) or O(R * C); each query O(1). Space: O(n) or O(R * C). Updates are not supported efficiently; a Fenwick tree gives O(log n) for both updates and queries.
By level
Fresher: Builds the 1D prefix array and answers queries correctly, explaining the running-total idea. Should explain why prefix[0] is 0.
Mid: Implements the 2D version with inclusion and exclusion and explains the zero-padding choice. Tests queries that touch the first row or column.
Senior: Discusses Fenwick and segment trees for updates, difference arrays, memory for huge grids and numeric overflow in fixed-width languages. Can estimate memory for a large grid and choose integer types sensibly.
Key points
- prefix[i] = sum of the first i values
- Range sum = prefix[r + 1] - prefix[l]
- A leading zero removes the index-0 special case
- 2D uses inclusion and exclusion with four lookups
- Use a Fenwick or segment tree if values change
Common mistakes
- Off-by-one errors when prefix has no leading zero
- Forgetting to add back the corner in 2D
- Recomputing sums per query
- Using prefix sums when the data changes often
Follow-ups
- How would you support updates?
- How do difference arrays apply range increments in O(1)?
- How do you count subarrays with sum k using prefix sums?
Tips
- Write the formula with a tiny example first
- Draw the four rectangles for 2D
- Mention the update limitation
Evaluation rubric
- Correct 1D and 2D formulas
- Handles boundaries cleanly
- States build and query complexity
- Knows when prefix sums are not enough