Skip to content
StackDecode
Array techniquesAnimated

Difference Array

Record range additions as two edits, then prefix-sum to apply them all.

Time

O(1) update, O(n) rebuild

Extra space

O(n)

Use it for

Many range-update operations.

How it works

  1. Adding a value to a whole range is slow if you touch every cell.
  2. Keep a difference array D where D[i] = a[i] − a[i−1].
  3. To add x to [l, r], do D[l] += x and D[r+1] −= x: just two edits.
  4. At the end, prefix-sum D to get the real array. Many updates cost O(1) each, then one O(n) rebuild.

Watch it run

Loading animation…