Skip to contentKEEP THE CRAFTTHE SANCTUARY

Difference Array

Record where each inclusive range addition starts and where it stops, then materialize all final values with one prefix pass. This separates cheap offline updates from the later cost of observing every position.

1 practice exercise5 interview problems

Recognize it when Many additive range updates can be collected before final values are needed.

Checking your account…

Difference Array Code Labs

Store a Change Rather Than Rewriting a Range

After understanding prefix accumulation, reverse the question: if adding 3 to positions 1 through 3 affects a constant region, only two boundaries explain the change. Start that contribution at 1 and cancel it at 4. Overlapping updates add their effects, so a boundary slot accumulates deltas rather than replacing its previous value.

Make the Endpoint Convention Explicit

These Labs use inclusive left/right indices. The cancellation belongs at right+1, because right itself still receives the addition. An update reaching the final index needs no cancellation inside the returned length. Updates are assumed to satisfy 0 <= left <= right < length; a zero-length input has no valid nonempty update.

Trace Difference Boundaries

Reference
def difference_trace(length,updates):
    difference=[0]*(length+1);trace=[]
    for left,right,delta in updates:
        difference[left]+=delta
        if right+1<length:difference[right+1]-=delta
        trace.append(difference[:length])
    return trace
Practice

Implement difference_trace(length,updates). Each update is [left,right,delta] inclusive; return the difference array after each update.

Public tests

  • Add at start and subtract after end

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Difference Boundaries

def difference_trace(length,updates):
    difference=[0]*(length+1);trace=[]
    for left,right,delta in updates:
        difference[left]+=delta
        if right+1<length:difference[right+1]-=delta
        trace.append(difference[:length])
    return trace

Accumulate Two Overlapping Boundary Effects

The existing trace Lab with length 5 and inclusive updates [1,3,+2], then [2,4,-1], records changes, not final values.

Step Executed statement State Why
Initialize difference=[0]*(length+1);trace=[] difference=[0,0,0,0,0,0] No update contributes yet; only the first length entries will be shown.
Start +2 difference[left]+=delta difference[1]=2 The addition starts at its inclusive left endpoint.
Stop after 3 if right+1<length:difference[right+1]-=delta difference[4]=-2 Index 3 remains covered; index 4 cancels the contribution.
Snapshot first update trace.append(difference[:length]) trace=[[0,2,0,0,-2]] The slice copies the current boundary representation.
Start -1 at 2 difference[left]+=delta difference[2]=-1 Negative additions superimpose on the earlier effect.
Update reaches end if right+1<length:difference[right+1]-=delta right+1=5; cancellation branch skipped No returned position exists after the inclusive end 4.
Return snapshots return trace [[0,2,0,0,-2],[0,2,-1,0,-2]] A later prefix pass, rather than these deltas themselves, gives final values.
Print Output
print(difference_trace(5, [[1, 3, 2], [2, 4, -1]])) [[0, 2, 0, 0, -2], [0, 2, -1, 0, -2]]

Carry Active Contributions Across the Array

The materialization Lab adds each difference entry to current and emits that running total. A cancellation changes current for subsequent positions rather than erasing a previously emitted value. Positive and negative deltas follow the same rule. This is the prefix identity applied to changes instead of original values.

Apply Range Increments

Reference
def apply_increments(length,updates):
    difference=[0]*(length+1)
    for left,right,delta in updates:
        difference[left]+=delta
        if right+1<length:difference[right+1]-=delta
    values=[];current=0
    for index in range(length):current+=difference[index];values.append(current)
    return values
Practice

Implement apply_increments(length,updates). Return final values after inclusive range additions.

Public tests

  • Reconstruct with one prefix pass

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Apply Range Increments

def apply_increments(length,updates):
    difference=[0]*(length+1)
    for left,right,delta in updates:
        difference[left]+=delta
        if right+1<length:difference[right+1]-=delta
    values=[];current=0
    for index in range(length):current+=difference[index];values.append(current)
    return values

Separate Update Cost from Snapshot Cost

Each boundary update is O(1), but printing the entire difference array after each of u updates copies n values u times. The trace Lab intentionally pays O(un) time and output space for those snapshots. The final-value Lab performs one O(n) reconstruction after O(u) updates, giving O(n+u) total time and O(n) space.

Explain the Offline Choice in an Interview

Choose differences when intermediate answers are unnecessary. If updates and queries alternate, rebuilding after each update loses the advantage; an update-aware Fenwick or segment tree is the nearest alternative. Demonstrate one overlapping update and one update touching the last index, then explain exactly where an effect stops. Boundary deltas are an addition-specific encoding, not a replacement for every form of range update.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Offline range additions and one reconstructionO(n + u)O(n + u)The final-value Lab touches two boundaries per update and scans n positions once.

Space

O(n) working and result storage; storing u full trace snapshots adds O(un) output.

Assumptions

  • The trace Lab slices n entries after every update, so its time and output are O(un), unlike the O(n+u) materialization Lab.
  • Python list slices copy values; independently copied difference snapshots preserve past state but have a real O(n) cost each.

Invariants Worth Saying Aloud

  1. A delta begins contributing at left and stops contributing at right+1, when that boundary is inside the result.
  2. During reconstruction, current equals the sum of all updates whose inclusive ranges cover the current index.

When To Use Or Avoid Difference Array

Use It When

  • Apply offline inclusive additions over known valid indices and reconstruct once.
  • Combine overlapping positive and negative deltas through addition at the same boundaries.

Choose Another Tool When

  • Use a Fenwick or segment tree when updates and value/range queries interleave.
  • Use a direct loop for one tiny update; a difference array does not make nonlinear updates or immediate full snapshots constant time.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Canceling at the inclusive right endpoint

Canceling +3 at right=2 means position 2 no longer receives the update, shortening the requested range.

Prevent it: Place the stop delta after right, unless it lies outside the returned array.

Avoid

difference[left] += delta
difference[right] -= delta

Use instead

difference[left] += delta
difference[right+1] -= delta

Replacing an earlier boundary contribution

Two updates beginning at the same left position contribute 2 and 3; assignment overwrites the earlier effect instead of combining them.

Prevent it: Use += for starts and -= for stops so overlapping contributions superimpose.

Avoid

difference[left] = delta

Use instead

difference[left] += delta

Returning differences as final values

The delta sequence [2, 0, -2] represents final values [2, 2, 0]; copying deltas exposes changes rather than active totals.

Prevent it: Accumulate current before emitting each reconstructed value.

Avoid

values = list(difference)

Use instead

values=[]
current=0
for delta in difference:
    current += delta
    values.append(current)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.