M16 · Prefix Sum and Difference Array

Prefix Sums and Difference Arrays

A prefix array turns every range-sum question into one subtraction. Its inverse, the difference array, turns every range update into two writes. This lesson builds both step by step, proves the formulas, covers the n + 1 sizing that removes edge cases, and shows where they combine with hashing.

~35 minIntermediateC# · Python · Java · C++
Curriculum: M16 Prefix Sum and Difference Array · 1 of 1 lessons available

You will be able to

  • Build a prefix array of length n + 1 and explain why prefix[0] = 0 removes the special case for ranges starting at 0.
  • Answer an inclusive range sum with prefix[to + 1] − prefix[from] and justify the formula.
  • Record a range update in a difference array with two writes, and apply many updates in one O(n) pass.
  • Compare the costs (O(n) build, O(1) query, O(n + u) for u updates) with the direct approach.
  • Choose 64-bit prefix values in C#, Java and C++, and know the built-ins (accumulate, partial_sum).

Helpful before this lesson

  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

Think of a car's odometer. To know how far you drove between two stops you do not add up every road segment; you subtract the two odometer readings. A prefix array is an odometer for an array: prefix[i] is the total of everything before position i. Any stretch is then the difference of two readings.

A difference array runs the idea backwards. Instead of storing values, it stores how much each value differs from the one before. Adding 5 to a whole stretch changes only two differences: the step up where the stretch starts and the step down just after it ends.

Building the prefix array

prefix = array of n + 1 zeros            # prefix[0] = 0: the empty sum
for i in 0 .. n-1:
    prefix[i + 1] = prefix[i] + values[i]

So prefix[i] = values[0] + … + values[i − 1]: the sum of the first i values. For values = [3, 1, 4, 1, 5, 9, 2, 6] that is [0, 3, 4, 8, 9, 14, 23, 25, 31].

The extra cell is deliberate. With n + 1 cells, the formula below works for every range, including ranges that start at index 0, with no if. In the lab's 3D view each prefix[i] sits on the boundary just left of values[i], which makes the formula visible: a range is fenced by two boundaries.

Answering a range sum

sum(values[from..to]) = prefix[to + 1] - prefix[from]       # inclusive range

Why it holds: prefix[to + 1] is the sum of values[0..to], and prefix[from] is the sum of values[0..from − 1]. Subtracting removes the shared beginning and leaves exactly values[from..to]. In the example, the sum of values[2..5] is prefix[6] − prefix[2] = 23 − 4 = 19, and it costs two reads whether the range holds one value or a million.

Prefix sums work with negative values too (the running total just goes down as well as up), and they need no ordering of any kind. They do need a static array: changing one value invalidates every prefix after it, an O(n) rebuild. For arrays that change between queries, a Fenwick tree or segment tree gives O(log n) updates and queries.

Difference arrays: many range updates

Now the opposite workload: apply u updates of the form "add delta to values[from..to]", and only look at the array afterwards. Doing each update directly costs up to n writes, O(n·u).

diff = array of n + 1 zeros               # one spare cell
for each update (from, to, delta):
    diff[from]   += delta                 # the change starts here
    diff[to + 1] -= delta                 # and stops after `to`
running = 0
for i in 0 .. n-1:
    running += diff[i]
    result[i] = values[i] + running

Why it holds: after the loop, running at index i is diff[0] + … + diff[i], a prefix sum of the difference array. An update (from, to, delta) contributes +delta to that sum for every i ≥ from and cancels out with −delta for every i ≥ to + 1. So it adds delta exactly for from ≤ i ≤ to, and updates simply add up. Each update costs two writes no matter how long its range, and one O(n) pass applies them all.

The spare cell diff[n] exists so that an update ending at the last index has somewhere to write its end marker; it is never read (see the Update to the end preset).

Complexity

Task Direct With the technique Extra space
q range-sum queries on a static array O(n·q) worst case O(n) build + O(1) per query n + 1 cells
u range updates, then read the array O(n·u) worst case O(1) per update + one O(n) pass n + 1 cells
Point update between queries O(1) O(n) rebuild (use a Fenwick tree instead) —

Both techniques trade memory for time: n + 1 extra cells, usually 64-bit ones.

Where prefix sums show up

  • Prefix sums with a hash map. "How many subarrays sum to exactly k?" becomes "how many earlier prefixes equal prefix[i] − k?" One pass with a map of prefix counts gives O(n), negative values included. Practise it in How many stretches add up to k?.
  • Balance points. An index where the left and right sides weigh the same satisfies prefix[i] = total − prefix[i + 1]: Where do both sides weigh the same?.
  • Prefix products. The same idea with multiplication, from both ends, avoids division: Every product but your own.
  • 2D prefix sums. P[r][c] holds the sum of the rectangle above and left of (r, c); any rectangle sum is then P[r2+1][c2+1] − P[r1][c2+1] − P[r2+1][c1] + P[r1][c1] (inclusion–exclusion).

Language notes

Overflow. The prefix of n 32-bit values can be up to n times larger than any value, so the listings store prefixes and differences as long (C#, Java) or std::int64_t (C++). In C# and Java an int prefix would wrap around silently; in C++ signed overflow is undefined behaviour. Python integers have arbitrary precision. 64 bits is enough for any array of 32-bit values that fits in memory: even 2³¹ values of magnitude 2³¹ sum to at most 2⁶², below the 2⁶³ limit.

Built-ins.

Language Running totals Notes
C# no direct built-in; a loop, or values.Aggregate(...) for a single total write the loop for a prefix array
Python list(itertools.accumulate(values, initial=0)) initial=0 (Python 3.8+) gives exactly the n + 1 layout
Java Arrays.parallelPrefix(long[] array, Long::sum) in place, on a copy you made as long[]; no leading 0
C++ std::partial_sum, std::inclusive_scan (C++17) write into a std::vector<std::int64_t> so the sums are 64-bit; no leading 0

The C++ test checks the listing against std::partial_sum, and the Python test against itertools.accumulate.

The teaching implementation

Build / build_prefix, RangeSum / range_sum and ApplyRangeAdds / apply_range_adds are written the same way in all four languages. Each language reads one shared fixture (empty array, one value, whole-array and single-cell ranges, negatives, nested and cancelling updates, extremes) and compares its results with summing and updating every range directly on 1,000 random arrays. Ranges are inclusive and must satisfy 0 ≤ from ≤ to < n; the listings document this precondition rather than checking it, and the lab rejects bad ranges before running.

Common mistakes

  • A prefix array of length n. Then ranges starting at 0 need a special case, and prefix[to] − prefix[from − 1] reads index −1. Use n + 1 cells.
  • Mixing inclusive and exclusive ends. prefix[to + 1] − prefix[from] is for the inclusive range [from, to]; for a half-open [from, to) it is prefix[to] − prefix[from].
  • Forgetting the end marker in a difference array, so the update runs to the end of the array.
  • No spare cell, so an update ending at n − 1 writes out of bounds.
  • Reusing a prefix array after the values changed.

Edge cases

  • Empty array: the prefix array is [0]; there are no valid ranges.
  • One value: prefix = [0, v]; the only range sum is v.
  • An update with delta = 0, or two updates that cancel: the array is unchanged.
  • Ranges covering the whole array: prefix[n] − prefix[0], the total.

Worked practice

1. Build the prefix array of [2, −1, 3] and compute the sum of values[1..2].

Answer

prefix = [0, 2, 1, 4]. Sum of values[1..2] = prefix[3] − prefix[1] = 4 − 2 = 2 (−1 + 3).

2. Apply "add 3 to [1, 4]" and "add −1 to [0, 2]" to eight zeros with a difference array.

Answer

diff[1] += 3, diff[5] −= 3, diff[0] −= 1, diff[3] += 1 gives diff = [−1, 3, 0, 1, 0, −3, 0, 0, 0]. Running sums: [−1, 2, 2, 3, 3, 0, 0, 0].

3. How many subarrays of [1, 2, 3] sum to 3, using prefixes?

Answer

Prefixes [0, 1, 3, 6]. Count pairs i < j with prefix[j] − prefix[i] = 3: (0, 2) gives [1, 2] and (2, 3) gives [3]. Two subarrays.

4. Why does a difference array not help if you must read the array after every update?

Answer

Reading a value needs the running sum up to that index, which is O(n) to recompute after each update. The difference array wins only when updates are batched and read once at the end. For interleaved updates and reads, use a Fenwick tree or a segment tree.

Summary

  • prefix[i] = sum of the first i values; n + 1 cells with prefix[0] = 0.
  • Range sum [from, to] = prefix[to + 1] − prefix[from]: O(1) after an O(n) build.
  • Difference array: two writes per range update, one O(n) running sum to apply them all.
  • The two are inverses: prefix-summing a difference array gives back the values.
  • Store sums in 64 bits in C#, Java and C++.

Full implementation

Prefix sums and the difference array in four languages, each checked against one shared fixture (empty array, one value, whole-array and single-cell ranges, negatives, nested and cancelling updates, extremes) and 1,000 random arrays compared with summing and updating every range directly.

namespace Bekadan.Dsa.Examples.ArrayPatterns;
 
/// <summary>
/// Prefix sums (O(n) build, O(1) range-sum query) and difference arrays
/// (O(1) per range update, O(n) to apply them all). Sums are <see cref="long"/>:
/// n ints can add up to more than int.MaxValue.
/// Ranges are inclusive and must satisfy 0 &lt;= from &lt;= to &lt; n.
/// </summary>
public static class PrefixSums
{
    /// <summary>prefix[i] = values[0] + … + values[i - 1]; prefix[0] = 0. Length n + 1.</summary>
    public static long[] Build(ReadOnlySpan<int> values)
    {
        var prefix = new long[values.Length + 1];  // prefix[0] = 0: the empty sum
        for (int i = 0; i < values.Length; i++)
            prefix[i + 1] = prefix[i] + values[i];
        return prefix;
    }
 
    /// <summary>values[from] + … + values[to], from a prefix array made by <see cref="Build"/>.</summary>
    public static long RangeSum(long[] prefix, int from, int to)
    {
        return prefix[to + 1] - prefix[from];
    }
 
    /// <summary>
    /// Returns a copy of <paramref name="values"/> with every update applied:
    /// update (from, to, delta) adds delta to values[from..to].
    /// </summary>
    public static long[] ApplyRangeAdds(ReadOnlySpan<int> values, IEnumerable<(int From, int To, int Delta)> updates)
    {
        var diff = new long[values.Length + 1];  // one spare cell for to = n - 1
        foreach (var (from, to, delta) in updates)
        {
            diff[from] += delta;
            diff[to + 1] -= delta;
        }
        var result = new long[values.Length];
        long running = 0;
        for (int i = 0; i < values.Length; i++)
        {
            running += diff[i];
            result[i] = values[i] + running;
        }
        return result;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/ArrayPatterns/PrefixSums.cs

"""Prefix sums and difference arrays.
 
build is O(n) and range_sum O(1); apply_range_adds is O(1) per update plus one
O(n) pass. Ranges are inclusive with 0 <= start <= end < n. Python ints never
overflow (itertools.accumulate builds the same running totals).
"""
 
from collections.abc import Iterable, Sequence
 
 
def build(values: Sequence[int]) -> list[int]:
    """prefix[i] = values[0] + ... + values[i - 1]; prefix[0] = 0. Length n + 1."""
    prefix = [0] * (len(values) + 1)  # prefix[0] = 0: the empty sum
    for i in range(len(values)):
        prefix[i + 1] = prefix[i] + values[i]
    return prefix
 
 
def range_sum(prefix: Sequence[int], start: int, end: int) -> int:
    """values[start] + ... + values[end], from a prefix list made by build."""
    return prefix[end + 1] - prefix[start]
 
 
def apply_range_adds(values: Sequence[int], updates: Iterable[tuple[int, int, int]]) -> list[int]:
    """A copy of values with every update (start, end, delta) applied to values[start..end]."""
    diff = [0] * (len(values) + 1)  # one spare cell for end = n - 1
    for start, end, delta in updates:
        diff[start] += delta
        diff[end + 1] -= delta
    result = [0] * len(values)
    running = 0
    for i in range(len(values)):
        running += diff[i]
        result[i] = values[i] + running
    return result

Tested on CPython 3.14.0 · examples/python/dsa_examples/prefix_sums.py

package dev.bekadan.dsa.patterns;
 
/**
 * Prefix sums (O(n) build, O(1) range-sum query) and difference arrays (O(1)
 * per range update, O(n) to apply them all). Sums are {@code long}: n ints can
 * add up to more than Integer.MAX_VALUE. Ranges are inclusive and must satisfy
 * 0 &lt;= from &lt;= to &lt; n.
 */
public final class PrefixSums {
    private PrefixSums() {
    }
 
    /** prefix[i] = values[0] + ... + values[i - 1]; prefix[0] = 0. Length n + 1. */
    public static long[] build(int[] values) {
        long[] prefix = new long[values.length + 1]; // prefix[0] = 0: the empty sum
        for (int i = 0; i < values.length; i++) {
            prefix[i + 1] = prefix[i] + values[i];
        }
        return prefix;
    }
 
    /** values[from] + ... + values[to], from a prefix array made by {@link #build}. */
    public static long rangeSum(long[] prefix, int from, int to) {
        return prefix[to + 1] - prefix[from];
    }
 
    /**
     * Returns a copy of values with every update applied: each row
     * {from, to, delta} adds delta to values[from..to].
     */
    public static long[] applyRangeAdds(int[] values, int[][] updates) {
        long[] diff = new long[values.length + 1]; // one spare cell for to = n - 1
        for (int[] update : updates) {
            diff[update[0]] += update[2];
            diff[update[1] + 1] -= update[2];
        }
        long[] result = new long[values.length];
        long running = 0;
        for (int i = 0; i < values.length; i++) {
            running += diff[i];
            result[i] = values[i] + running;
        }
        return result;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/patterns/PrefixSums.java

#pragma once
 
#include <cstddef>
#include <cstdint>
#include <span>
#include <vector>
 
namespace bekadan::dsa {
 
// Prefix sums (O(n) build, O(1) range-sum query) and difference arrays (O(1) per
// range update, O(n) to apply them all). Sums are std::int64_t: n ints can add
// up to more than INT_MAX, and signed overflow is undefined behaviour.
// Ranges are inclusive and must satisfy 0 <= from <= to < n (not checked).
 
struct RangeAdd {
    std::size_t from;
    std::size_t to;
    int delta;
};
 
// prefix[i] = values[0] + ... + values[i - 1]; prefix[0] = 0. Size n + 1.
// std::partial_sum computes the same running totals without the leading 0.
inline std::vector<std::int64_t> build_prefix(std::span<const int> values) {
    std::vector<std::int64_t> prefix(values.size() + 1, 0);  // prefix[0] = 0: the empty sum
    for (std::size_t i = 0; i < values.size(); ++i) {
        prefix[i + 1] = prefix[i] + values[i];
    }
    return prefix;
}
 
// values[from] + ... + values[to], from a prefix vector made by build_prefix.
inline std::int64_t range_sum(std::span<const std::int64_t> prefix, std::size_t from, std::size_t to) {
    return prefix[to + 1] - prefix[from];
}
 
// A copy of values with every update applied (delta added to values[from..to]).
inline std::vector<std::int64_t> apply_range_adds(std::span<const int> values, std::span<const RangeAdd> updates) {
    std::vector<std::int64_t> diff(values.size() + 1, 0);  // one spare cell for to = n - 1
    for (const auto& update : updates) {
        diff[update.from] += update.delta;
        diff[update.to + 1] -= update.delta;
    }
    std::vector<std::int64_t> result(values.size());
    std::int64_t running = 0;
    for (std::size_t i = 0; i < values.size(); ++i) {
        running += diff[i];
        result[i] = values[i] + running;
    }
    return result;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/prefix_sums.hpp

References