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
- Adding a value to a whole range is slow if you touch every cell.
- Keep a difference array D where D[i] = a[i] − a[i−1].
- To add x to [l, r], do D[l] += x and D[r+1] −= x: just two edits.
- 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…