DSA Trainer
← Foundations

Foundations · Unit 5

Prefix Sum

You are handed an array and asked, over and over, for the sum of a range: elements 2 through 5, then 0 through 3, then 4 through 7. The obvious approach adds up each range when asked. That is fine for one query, but if you have thousands of queries you re-add the same numbers endlessly, and the cost balloons.

A prefix sum fixes this by doing the adding once, up front. You build an array where each slot holds the running total up to that point. After that, the sum of any range is a single subtraction of two precomputed totals, in constant time. The same idea, cumulative totals you can difference, unlocks a surprising trick: paired with a hash map, prefix sums can count how many subarrays add up to a target, in one pass.

This unit builds the prefix sum array, shows why the range subtraction works, and then connects it to the hash map for the problems that make prefix sum click. It is one of the highest-return techniques for the effort it takes to learn.

Goal: Precompute cumulative sums so any range total is O(1), and combine prefix sums with a hash map to count subarrays.
Lesson 1 of 60%

You’re not signed in. Your progress here won’t be saved.

The pain: summing the same range over and over

Say you will be asked for many range sums of [3, 1, 4, 1, 5, 9, 2]: the sum from index 1 to 4, then 0 to 5, then 2 to 6. Answering each by adding the elements in the range works, but a range can be nearly the whole array, so each query costs up to n additions.

With q queries that is about q times n work, and most of it is re-adding numbers you already summed for an overlapping range. The repetition is the waste prefix sums remove.

You answer q range-sum queries on an n-element array by adding up each range when asked. Roughly what is the total cost?

Premium practice

The drills and graded test are premium

The lessons above are free. The interactive practice that turns recognizing the pattern into recalling it on a blank page unlocks with premium:

  • 3 applied drills: train spotting when the concept applies
  • A 5-question graded test to clear the unit
  • The full guided problem ladder with faded hints, plus the cold-read capstone
Unlock everything →

From $6/month. Cancel anytime.