Pay once, query often.
Precompute a cumulative table and answer half-open range sums in constant time.
01 Model the idea
A prefix-sum table stores the sum before each position, including an initial zero. The sum over [left,right) is prefix[right]−prefix[left]. This spends linear preprocessing and storage to support many constant-time static range queries. If values change frequently, a Fenwick or segment tree may be a better fit; a prefix table does not automatically update itself.
prefix[i] equals the sum of the first i input values.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
START a zero prefix
APPEND each cumulative sum
ANSWER a range by subtracting its boundary prefixes| Prefix length | Cumulative sum |
|---|---|
| 0 | 0 |
| 1 | 3 |
| 2 | 4 |
| 3 | 8 |
| 4 | 9 |
| 5 | 14 |
03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
values = [3, 1, 4, 1, 5]
prefix = [0]
for value in values: prefix.append(prefix[-1] + value)
def range_sum(left, right):
if not 0 <= left <= right <= len(values): raise ValueError("Invalid range")
return prefix[right] - prefix[left]
print(range_sum(1, 4))
print(range_sum(2, 2))6 0
- 1
The extra zero makes an empty prefix and a range starting at zero use the same formula as every other valid range.
- 2
The right endpoint is excluded. That convention makes a range’s length right-left and gives empty ranges a clean zero result.
- 3
A static data mutation invalidates later prefix values. Rebuild intentionally or use a data structure designed for updates; do not keep serving stale aggregates.
04 Count the cost
O(n) preprocessing; O(1) per static sum query
O(n) prefix table
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Compare every valid range query with a direct sum on a small fixture.
Reveal one possible solution +
values = [3, 1, 4]
prefix = [0]
for value in values: prefix.append(prefix[-1] + value)
for left in range(len(values) + 1):
for right in range(left, len(values) + 1):
assert prefix[right] - prefix[left] == sum(values[left:right])
print("All small ranges verified")06 Check your reasoning
What is the static sum over [left,right)?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.