Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Reusable problem patterns
EXPERIMENT 63 / 66

Pay once, query often.

Precompute a cumulative table and answer half-open range sums in constant time.

BY NAVAN SAMI◷ 8 MIN READSTRETCHALGORITHM

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.

THE THING THAT MUST STAY TRUE

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.

the_strategy.txt
START a zero prefix
APPEND each cumulative sum
ANSWER a range by subtracting its boundary prefixes
A worked trace for this experiment
Prefix lengthCumulative sum
00
13
24
38
49
514

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

prefix_sums.py
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))
↳ EXPECTED OUTPUT
6
0
  1. 1

    The extra zero makes an empty prefix and a range starting at zero use the same formula as every other valid range.

  2. 2

    The right endpoint is excluded. That convention makes a range’s length right-left and gives empty ranges a clean zero result.

  3. 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

TIME

O(n) preprocessing; O(1) per static sum query

SPACE

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

A SMALL MISSION

Compare every valid range query with a direct sum on a small fixture.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

What is the static sum over [left,right)?

ANOTHER PATTERN IN YOUR TOOLKIT.

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.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.