PrepStack · Markdown HTML

Prefix sum / range aggregation

Prefix, difference, and hashed state · HTML

Formal shape

Define prefix[0]=0 and prefix[i+1]=prefix[i]+a[i]. The sum of half-open [l,r) is prefix[r]-prefix[l].

Recognition signals

False friends

SignalWhy it is different
Frequent point updatesChanging one value invalidates every later plain prefix; use a Fenwick or segment tree.
Range maximumMax has no inverse subtraction, so two ordinary prefixes cannot recover an arbitrary interval.

Core invariant

prefix[i] always aggregates exactly the first i elements a[0:i]; i denotes a count, not an original element index.

State, transition, and processing order

ItemDefinition
StateA length-n+1 prefix array, query endpoints l/r, and one consistent half-open interval convention.
TransitionDuring construction set prefix[i+1]=prefix[i]+a[i]; during a query subtract the left prefix from the right prefix.
Frontier / orderConstruction advances left to right; after it finishes, all range queries are independent.

Python skeleton

def build_prefix(values):
    prefix = [0]
    for value in values:
        prefix.append(prefix[-1] + value)
    return prefix

def range_sum(prefix, left, right):
    # Sum over half-open interval [left, right).
    if not (0 <= left <= right < len(prefix)):
        raise IndexError('invalid range')
    return prefix[right] - prefix[left]

Correctness sketch

  1. Induction on the recurrence gives prefix[i]=a[0]+…+a[i-1].
  2. prefix[r] consists of [0,l) plus [l,r); subtracting prefix[l] cancels the shared first part exactly.
  3. A query reads two verified prefixes and therefore returns the precise interval aggregate.

Complexity

TimeSpaceParameters
O(n) preprocessing and O(1) per queryO(n)n is array length; q queries total O(n+q).

Edge cases

Error patterns

PatternWhy it fails / fix
Building only n prefix slotsWithout the leading zero, l=0 needs special handling and off-by-one risk rises.
Mixing closed and half-open rangesWrite [l,r) or [l,r] explicitly before using a formula.
Rebuilding after every updateFrequent changes require a dynamic range structure.

Selection and exclusion rules

RelationTemplateBoundary
dynamic extensionFenwick treePrefix sums need point updates
algebraic foundationPrefix state plus frequency hashUnderstanding why an interval is a difference of prefixes.
algebraic analogueRolling hash / Rabin-KarpUnderstanding range extraction from two prefixes
range-query alternativeFixed-size sliding windowOffline fixed-window sums can also be differences of prefixes.
invertible static alternativeSparse table static RMQThe operation is addition

Original micro-example

PartDetail
ResultThe interval sum is 5.
SetupValues [3,-1,4,2], query half-open [1,4).
Traceprefix=[0,3,2,6,8]; compute 8-3.

Recall prompts

My notes