← Lessons

quiz vs the machine

Silver1110

Algorithms

Prefix Sums

Precompute running totals so any range sum becomes a single subtraction.

3 min read · intro · beat Silver to climb

Prefix Sums

A prefix sum array stores, at each position, the total of all elements up to that point. With it, the sum of any contiguous range becomes a single subtraction instead of a loop, which is a huge win when you answer many range queries.

Building it

Walk the original array once, keeping a running total. Position i of the prefix array holds the sum of the first i elements. Building this takes one linear pass.

Querying a range

To get the sum of a range from index l to index r, take the prefix value at r and subtract the prefix value just before l. That single operation replaces a loop over the range, so each query runs in constant time no matter how wide the range is.

This precompute once, query many pattern is the heart of prefix sums. The same idea extends to two dimensions for rectangle sums in a grid, and a related difference array lets you apply many range updates cheaply.

Key idea

Precomputing running totals turns every range sum query into one subtraction, trading a linear precompute for constant time answers.

Check yourself

Answer to earn rating on the learn ladder.

1. After building a prefix sum array, how long does a range sum query take?

2. How do you compute the sum of the range from l to r?