Algorithm · Array techniques · build O(n), query O(1)
Prefix sums and difference arrays
Precompute running totals once, then answer any range sum in O(1); the difference array does the reverse for range updates.
The full derivation, edge cases and exercises are in the lesson Prefix sums and difference arrays. Open it full width in the playground.
On this page
The idea
With P[i] = a[0] + … + a[i − 1], the sum of a[l … r] is P[r + 1] − P[l]. One O(n) pass pays for unlimited O(1) queries, as long as the array does not change.
A difference array stores D[i] = a[i] − a[i − 1]. Adding v to a whole range touches only D[l] and D[r + 1]; one prefix-sum pass rebuilds the array.
Steps
- Build P with P[0] = 0 and P[i + 1] = P[i] + a[i].
- Answer sum(l, r) as P[r + 1] − P[l].
- Range update: D[l] += v, D[r + 1] −= v; rebuild with a running sum.
Invariants
What holds at every step; the correctness argument rests on these.
- P[i] is the sum of the first i elements.
- The prefix sum of D reproduces the current array.
Complexity
| Case | Time | Extra space | Notes |
|---|---|---|---|
| Build | O(n) | O(n) | |
| Range sum query | O(1) | O(1) | |
| Range update (difference array) | O(1) | O(1) | O(n) to rebuild the array afterwards. |
When to use it
Use it when
- Many range-sum queries on static data; counting subarrays with a given sum (with a hash map).
Avoid it when
- Updates and queries interleave: a Fenwick or segment tree gives O(log n) for both.
Step through it
The interactive lab for prefix sums and difference arrays: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
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 <= from <= to < 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 <= from <= to < 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
Learn more
Lessons
- Prefix sums and difference arrays· M16 Prefix Sum and Difference Array
Data structures it uses
Problems, patterns and exercises
- PatternPrefix sums· O(n) build, O(1) per query
- ProblemWhere do both sides weigh the same?· beginner · O(n)
- ProblemHow many stretches add up to k?· intermediate · O(n) expected
- ProblemEvery product but your own· intermediate · O(n)