BeginnerCoder

Lesson 9 — Prefix sums

Prefix sums: precompute once, answer instantly

A prefix sum list stores running totals: pre[k] is the sum of the first k items. Building it takes one pass. After that, the sum of any range a[i..j] is just pre[j + 1] − pre[i] — one subtraction, no loop.

a   = [2, 4, 6]
pre = [0, 2, 6, 12]
# sum of a[1..2] = pre[3] - pre[1] = 12 - 2 = 10

Why it matters: if you must answer thousands of "sum from day i to day j" questions, this turns each answer from O(n) into O(1) (one step).

Want it another way?
Task

Finish range_sum(i, j) with one subtraction of two prefix values. Expected: 18, 30, 6.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.