Esercitati in matematica discreta

Algorithms / Difference Arrays

Least You Need to Know: Difference Arrays, Boundary Marking, and Range Updates

Difference arrays invert the prefix-sum idea: instead of storing cumulative totals directly, they store **where changes begin and end**. After marking update boundaries, one prefix sweep reconstructs the final values.

The least you need to know

Key notation

diff[l] += x start applying +x at position l
diff[r+1] -= x stop applying +x after position r
prefix of diff reconstructed final array

Tiny worked example

  • To add `+3` on interval `[2, 4]`, mark `diff[2] += 3` and `diff[5] -= 3`.
  • After all updates, take prefix sums of `diff`.
  • The running total applies the update exactly on positions `2, 3, 4`.
  • This converts repeated range updates into constant-time boundary edits plus one final sweep.

Common mistakes

How to recognize this kind of problem

Start practice