Beginner 13 min

Arrays and prefix sums

Use indexed storage and build running totals to answer many range queries.

Use the index to name a position

An array puts values in order, with a zero-based index for each position. When you repeatedly need to add values from different intervals, scanning the same positions for each request can do unnecessary work.

How it works

Build a zero entry before the first balance. With [4, 2, 7], the cumulative totals become [0, 4, 6, 13]. The sum of positions 1 and 2 is 13 − 4 = 9, because subtracting the first prefix removes exactly the part outside that range.

Precompute the totals

prefix[i] is the sum of the first i values. Set prefix[0] to zero and add the next value to build each entry. For an inclusive interval from left through right, subtract prefix[left] from prefix[right + 1]. The build costs O(n) time and space. Each later sum takes O(1) time.

Code example

values = [3, 5, 2, 7]
prefix = [0]
for value in values:
    prefix.append(prefix[-1] + value)
left, right = 1, 3
print(prefix[right + 1] - prefix[left])

Check your understanding

Find the sum of the supplied zero-based interval. Include both endpoints.

See the example and explanation
Example 1
Given [3, 5, 2, 7], left = 1, right = 2
Answer 7
Example 2
Given [3, 5, 2, 7], left = 0, right = 0
Answer 3

To sum indices 1 through 2, take the sum of the first three entries and subtract the sum of the first one. That is 10 − 3 = 7. The single index 0 uses 3 − 0 = 3.

Open practice problem
Next lessonBig O and growth