Patterns (two pointers, windows, prefix sums) · build O(n), query O(1)
Prefix sums and difference arrays
Constant-time range sums after a linear build; range updates with a difference array.
The full explanation, derivation and practice are in the lesson Prefix sums and difference arrays.
Implementation
The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.
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