Prefix Sums

How prefix sums answer range-sum queries in constant time, how to count subarrays with a given sum, and what interviewers ask about them.

14 minLesson 6 of 6
On this page
  1. How prefix sums work
  2. Variants and when to use each
  3. Pitfalls in the range formula and the hash map
  4. In the interview
  5. What to practise next

A prefix sum array stores, for each position in an array, the total of all the items before it. Once it is built, the sum of any range of items is one subtraction instead of a loop. You reach for it when a problem asks for many range sums on the same array, or asks you to count or find ranges whose sum has a given property.

Without it, every query adds up its range from scratch, so answering many queries on a long array repeats the same additions over and over. Prefix sums do that work once, in a single pass, and every query after that takes constant time.

How prefix sums work

Build an array prefix in which prefix[i] is the sum of the first i items of the input. The entry prefix[0] is 0, the sum of no items, so prefix has one more entry than the input. Each entry is the previous entry plus one input item.

The sum of items l to r, both included, is everything up to and including item r, minus everything before item l:

sum(l..r) = prefix[r + 1] − prefix[l]

0 1 2 3 4 5 5 2 6 3 1 4 prefix[5] = 5 + 2 + 6 + 3 + 1 = 17 prefix[2] = 7 17 − 7 = 10 = 6 + 3 + 1
prefix[5] is the sum of items 0 to 4. Subtracting prefix[2], the sum of items 0 and 1, leaves the sum of items 2 to 4.

The tracer below builds the array for the numbers 5, 2, 6, 3, 1, 4 and then answers two queries from it.

Build the prefix sums, then answer range queriesUse the arrows or ← → keys
prefix[0] = 0for i from 0 to n - 1:  prefix[i + 1] = prefix[i] + nums[i]sum(l..r) = prefix[r + 1] - prefix[l]
  1. nums
    05
    12
    26
    33
    41
    54
    prefix
    00
    1
    2
    3
    4
    5
    6

    1The array starts with prefix[0] = 0, the sum of no items. It has 7 slots for 6 numbers.

  2. nums
    05i
    12
    26
    33
    41
    54
    prefix
    00
    15
    2
    3
    4
    5
    6

    2prefix[1] is prefix[0] plus item 0, so 0 + 5 = 5.

  3. nums
    05
    12i
    26
    33
    41
    54
    prefix
    00
    15
    27
    3
    4
    5
    6

    3prefix[2] is 5 + 2 = 7.

  4. nums
    05
    12
    26i
    33
    41
    54
    prefix
    00
    15
    27
    313
    4
    5
    6

    4prefix[3] is 7 + 6 = 13.

  5. nums
    05
    12
    26
    33i
    41
    54
    prefix
    00
    15
    27
    313
    416
    5
    6

    5prefix[4] is 13 + 3 = 16.

  6. nums
    05
    12
    26
    33
    41i
    54
    prefix
    00
    15
    27
    313
    416
    517
    6

    6prefix[5] is 16 + 1 = 17.

  7. nums
    05
    12
    26
    33
    41
    54i
    prefix
    00
    15
    27
    313
    416
    517
    621

    7prefix[6] is 17 + 4 = 21, the sum of all six numbers.

  8. nums
    05
    12
    26l
    33
    41r
    54
    prefix
    00
    15
    27
    313
    416
    517
    621

    8To sum items 2 to 4, compute prefix[5] − prefix[2] = 17 − 7 = 10. Adding 6 + 3 + 1 directly gives the same result.

  9. nums
    05
    12
    26
    33
    41
    54
    prefix
    00
    15
    27
    313
    416
    517
    621
    items 0 to 3
    16
    items 1 to 5
    16

    9Every query costs one subtraction, however long the range is. Items 0 to 3 give 16 − 0 = 16, and items 1 to 5 give 21 − 5 = 16.

1 / 9
function buildPrefix(nums) {
  const prefix = [0];
  for (let i = 0; i < nums.length; i++) {
    prefix.push(prefix[i] + nums[i]);
  }
  return prefix;
}
 
// Sum of nums[l..r], both ends included.
function rangeSum(prefix, l, r) {
  return prefix[r + 1] - prefix[l];
}
 
const prefix = buildPrefix([5, 2, 6, 3, 1, 4]); // [0, 5, 7, 13, 16, 17, 21]
rangeSum(prefix, 2, 4); // 10
def build_prefix(nums):
    prefix = [0]
    for i in range(len(nums)):
        prefix.append(prefix[i] + nums[i])
    return prefix
 
# Sum of nums[l..r], both ends included.
def range_sum(prefix, l, r):
    return prefix[r + 1] - prefix[l]
 
prefix = build_prefix([5, 2, 6, 3, 1, 4])  # [0, 5, 7, 13, 16, 17, 21]
range_sum(prefix, 2, 4)  # 10
ApproachTimeSpaceWhy
Add up each range from scratchO(n) per queryO(1)q queries cost O(n · q).
Prefix sumsO(n) build, O(1) per queryO(n)The build is one pass, and each query is one subtraction, so q queries cost O(n + q).

Variants and when to use each

Counting subarrays with a given sum

A common problem gives an array and a target k and asks how many contiguous ranges add up to exactly k. A range ending at the current item sums to k when some earlier prefix sum equals the current prefix sum minus k. So you walk through the array once, keep the running total, and keep a hash map that counts how many times each prefix sum has appeared. At each item you add the number of earlier prefix sums equal to running − k to the answer, and then record the current prefix sum in the map.

The map starts as {0: 1}, which stands for the empty prefix before the first item. That entry is what lets ranges starting at the first item be counted.

This approach is needed because a sliding window only works when all values are non-negative. With negative values, extending a window can lower its sum and shrinking it can raise the sum, so the window has no rule for when to move. The prefix-sum identity does not depend on the sign of the values.

Count the ranges that add up to 2Use the arrows or ← → keys
seen = {0: 1}, running = 0, count = 0for x in nums:  running += x  count += seen[running - k]  (0 if missing)  seen[running] += 1
  1. nums
    02
    1-1
    23
    3-2
    42
    k
    2
    running
    0
    seen
    {0: 1}
    count
    0

    1Before any item, the prefix sum 0 has appeared once. This entry lets ranges that start at the first item be counted.

  2. nums
    02i
    1-1
    23
    3-2
    42
    k
    2
    running
    2
    need
    0
    seen
    {0: 1, 2: 1}
    count
    1

    2The running total is 2, so the map needs a 0, and it has one. That gives one range, [2].

  3. nums
    02
    1-1i
    23
    3-2
    42
    k
    2
    running
    1
    need
    -1
    seen
    {0: 1, 2: 1, 1: 1}
    count
    1

    3The running total is 1, so the map needs −1. It has never held −1, so no range ends here.

  4. nums
    02
    1-1
    23i
    3-2
    42
    k
    2
    running
    4
    need
    2
    seen
    {0: 1, 2: 1, 1: 1, 4: 1}
    count
    2

    4The running total is 4, so the map needs a 2. The 2 came from the total after item 0, so the range after it, [-1, 3], adds up to 2.

  5. nums
    02
    1-1
    23
    3-2i
    42
    k
    2
    running
    2
    need
    0
    seen
    {0: 1, 2: 2, 1: 1, 4: 1}
    count
    3

    5The running total is 2 again and the map has one 0, so the range [2, -1, 3, -2] counts.

  6. nums
    02
    1-1
    23
    3-2
    42i
    k
    2
    running
    4
    need
    2
    seen
    {0: 1, 2: 2, 1: 1, 4: 2}
    count
    5

    6The running total is 4 and the map has two 2s, so two ranges end here: [-1, 3, -2, 2] and [2].

  7. nums
    02
    1-1
    23
    3-2
    42
    count
    5
    all ranges
    15

    7Five ranges add up to 2. The pass made five lookups, while checking every range would mean examining all 15 of them.

1 / 7
function countRangesWithSum(nums, k) {
  const seen = new Map([[0, 1]]); // the empty prefix before the first item
  let running = 0;
  let count = 0;
  for (const x of nums) {
    running += x;
    count += seen.get(running - k) ?? 0;
    seen.set(running, (seen.get(running) ?? 0) + 1);
  }
  return count;
}
 
countRangesWithSum([2, -1, 3, -2, 2], 2); // 5
def count_ranges_with_sum(nums, k):
    seen = {0: 1}  # the empty prefix before the first item
    running = 0
    count = 0
    for x in nums:
        running += x
        count += seen.get(running - k, 0)
        seen[running] = seen.get(running, 0) + 1
    return count
 
count_ranges_with_sum([2, -1, 3, -2, 2], 2)  # 5
ApproachTimeSpaceWhy
Check every rangeO(n²)O(1)There are about n²/2 ranges.
Prefix sums with a hash mapO(n)O(n)One lookup and one update per item, and the map can hold n + 1 different totals.

Other properties of a prefix

The same idea works for any property that two equal prefixes would cancel out. To count ranges whose sum is divisible by k, store the prefix sum modulo k instead of the sum itself, because two prefixes with the same remainder differ by a multiple of k. In JavaScript the % operator returns a negative result for a negative number, so use ((x % k) + k) % k. To find the longest range with equal numbers of zeros and ones, treat each zero as −1, and the longest range with sum 0 is the gap between the two furthest-apart equal prefix sums. For that problem you store the first index at which each prefix sum appeared instead of a count.

Two-dimensional prefix sums

For a grid, let P[r][c] be the sum of the rectangle that covers every cell above row r and left of column c, so P has one extra row and one extra column of zeros. You build it in one pass with P[r + 1][c + 1] = grid[r][c] + P[r][c + 1] + P[r + 1][c] − P[r][c], where the last term removes the overlap that the two neighbours both include. The sum of the rectangle from row r1 to r2 and column c1 to c2, ends included, is P[r2 + 1][c2 + 1] − P[r1][c2 + 1] − P[r2 + 1][c1] + P[r1][c1]. That is four lookups for any rectangle, however large.

Difference arrays for range updates

A difference array is the reverse of a prefix sum. It is used when the problem applies many updates of the form "add v to every item from l to r" and only asks for the final array. Instead of touching every item in the range, you add v at index l and subtract v at index r + 1 in a separate array. When all updates are done, a single prefix-sum pass over that array gives the final values, so each update costs O(1) and the total is O(n + u) for u updates. This only works when you read the array after all updates; if queries are mixed in between, you need a Fenwick tree or segment tree.

When prefix sums do not apply

Prefix sums need the operation to be reversible, so that subtracting one prefix undoes the other. Sum, count and xor can be undone this way, but the minimum and maximum cannot, because you cannot subtract a minimum away from a larger range. Range minimum queries need a different structure, such as a sparse table or a segment tree.

They also assume the array does not change. If one item changes, every prefix after it is wrong, and rebuilding them costs O(n). When values are updated between queries, use a Fenwick tree or segment tree, which handles both an update and a range query in O(log n).

Pitfalls in the range formula and the hash map

In the interview

The signal is a problem that asks about a contiguous range and either repeats the query many times or asks you to count or find ranges. Phrases such as "sum of the items between index i and j", "number of subarrays with sum k", "subarray sum divisible by k" and "longest subarray with equal numbers of two values" all point to prefix sums. If the statement says that all numbers are positive and asks for the shortest or longest range, a sliding window may be enough, so ask whether negative numbers are allowed before you choose.

Questions to expect:

  • "Why is the prefix array one element longer than the input?" The extra first entry is the sum of no items. It lets the formula prefix[r + 1] − prefix[l] work when the range starts at index 0, without a special case.
  • "Why can't you use a sliding window to count subarrays with sum k?" A window moves based on whether its sum is too big or too small, which only makes sense when adding an item never lowers the sum. With negative values, a window that is too big can become correct after you extend it, so the window rule fails. The prefix-sum and hash map approach has no such requirement.
  • "Why do you start the map with a zero?" It represents the empty prefix before the first item. Without it, a range that starts at index 0 has no earlier prefix to match, and it is missed.
  • "What if the array is updated between queries?" One update invalidates every prefix after it, and rebuilding costs O(n) per update. A Fenwick tree or segment tree supports an update and a range sum in O(log n) each, so use one of those when updates and queries are mixed.
  • "Can you do the same for minimum or maximum?" No, because you cannot remove a minimum from a range by subtracting. A sparse table answers range minimum in O(1) after an O(n log n) build, and a segment tree handles it with updates.
  • "How would you count subarrays whose sum is divisible by k?" Keep a map of how many times each prefix sum remainder modulo k has appeared. Two prefixes with the same remainder differ by a multiple of k, so each new prefix adds the count of its own remainder to the answer. Normalise negative remainders first.
  • "How would you extend this to a matrix?" Build a two-dimensional prefix array and answer each rectangle with four lookups, adding two corners and subtracting two. Explain the overlap term, because that is where mistakes usually happen.
  • "Can you use less than O(n) extra space?" For a single query you can sum the range directly in O(1) space. For the counting problem you can only drop the map if you accept O(n²) time, so the extra space buys the speed.
Quick check

With prefix = [0, 5, 7, 13, 16, 17, 21], what is the sum of items 1 to 3?

Why does counting ranges with sum k use prefix sums and a hash map instead of a sliding window?

An array is queried for range sums, and between queries single values are changed. Which approach fits?

What to practise next

Solve Matching Receipts, which uses the same idea of looking up in a map the earlier value that completes the current one. Then read Segment and Fenwick Trees for range queries on data that changes.