awelgorithms

Range update is plus at L and minus at R+1

Updated

Add +v on inclusive [L, R]: d[L]+=v, and if R+1<n then d[R+1]-=v. Every index in L..R picks up +v on rebuild. Overlapping ranges wait; you only write d here.

What to focus on

If R=n-1 the minus is omitted (or written to an unused d[n]). Do not loop the range.

Worked examples

both writes

a = [4, 1, 9], add +2 on [0, 1]
  1. d = [4, -3, 8]
  2. d[0]+=2
  3. d[2]-=2
  4. d = [6, -3, 6]
  5. prefix 6, 3, 9

Result: a becomes [6, 3, 9]

to the end

a = [4, 1, 9, 1], add +5 on [1, 3]
  1. d = [4, -3, 8, -8]
  2. d[1]+=5
  3. R+1=4 is past n
  4. d = [4, 2, 8, -8]
  5. prefix 4, 6, 14, 6

Result: a becomes [4, 6, 14, 6]

one cell as range

a = [7], add +4 on [0, 0]
  1. d[0]+=4
  2. no R+1

Result: a becomes [11]

Try it

Write rangeAdd(d, L, R, v). d is the difference array. L is the left index. R is the right index. v is the amount to add. Write d[L] += v and, if R+1 < n, d[R+1] -= v. Rebuild once. Return a. [4, 1, 9] +2 on [0, 1] → [6, 3, 9] [4, 1, 9, 1] +5 on [1, 3] → [4, 6, 14, 6] [7] +4 on [0, 0] → [11]

a is a non-empty array of integers. 0 ≤ L ≤ R < n. v is an integer.