PrepStack · Markdown HTML

Difference array / batched range updates

Prefix, difference, and hashed state · HTML

Formal shape

To add delta on closed [l,r], do diff[l]+=delta and diff[r+1]-=delta when represented. Finally a[i]=base[i]+Σ_{j≤i}diff[j].

Recognition signals

False friends

SignalWhy it is different
Querying immediately after each updateUnintegrated diff cannot answer current values directly; use a Fenwick or segment tree for online operations.
Range assignmentOverwrite priority is not simple additive superposition, so two endpoint deltas are insufficient.

Core invariant

diff stores changes between adjacent real values; a range delta begins at l and is canceled completely at r+1.

State, transition, and processing order

ItemDefinition
StateA length-n or n+1 difference array, endpoints, delta, and running prefix during reconstruction.
TransitionWrite two events per update; after all updates, scan left to right with running+=diff[i] and apply it to output.
Frontier / orderUpdates have no pointwise frontier; during reconstruction, running is the sum of intervals that have started but not yet ended.

Python skeleton

def apply_range_adds(length, updates):
    diff = [0] * (length + 1)
    for left, right, delta in updates:
        if not (0 <= left <= right < length):
            raise IndexError('invalid update')
        diff[left] += delta
        diff[right + 1] -= delta
    result = [0] * length
    running = 0
    for i in range(length):
        running += diff[i]
        result[i] = running
    return result

Correctness sketch

  1. For one [l,r] update, its prefix contribution is zero before l, delta throughout l..r, and zero again after the negative event at r+1.
  2. Linearity lets events from many updates add in any order.
  3. The final prefix at each coordinate sums exactly all update intervals covering that coordinate.

Complexity

TimeSpaceParameters
O(q+n)O(n)q is update count and n coordinate length; each update is O(1), reconstruction O(n).

Edge cases

Error patterns

PatternWhy it fails / fix
Omitting cancellation at r+1The delta incorrectly leaks to every later coordinate.
Mixing closed and half-open endpointsClosed [l,r] cancels at r+1; half-open [l,r) cancels at r.
Reading diff directlydiff is a derivative and must be prefix-integrated into point values.

Selection and exclusion rules

RelationTemplateBoundary
online versionFenwick treeQueries must follow updates immediately.
sparse-coordinate generalizationSweep line with sorted eventsThe coordinate universe is huge and only sorted event points matter.
integration dualPrefix sum / range aggregationOne prefix pass turns changes back into values.

Original micro-example

PartDetail
ResultThe increment array is [0,4,6,6,2].
SetupLength 5; add 4 on [1,3] and 2 on [2,4].
TraceEvents are +4@1,-4@4,+2@2,-2@5; integrate left to right.

Recall prompts

My notes