Overlapping range updates accumulate
Updated
Each range add writes d independently. Overlap means some indices receive two +v's. Apply every d[L]+=v and d[R+1]-=v first; rebuild once. The prefix pass sums the stacked writes.
What to focus on
Do not rebuild between overlapping updates. Addition on d commutes.
Worked examples
overlap at index 1
a = [4, 1, 9], +2 on [0, 1] and +3 on [1, 2]- d starts [4, -3, 8]
- +2: d[0]+=2, d[2]-=2 → [6, -3, 6]
- +3: d[1]+=3, no d[3] → [6, 0, 6]
- prefix 6, 6, 12
Result: a becomes [6, 6, 12]
full overlap
a = [4, 1, 9], +1 on [0, 2] twice- first: d[0]+=1 → [5, -3, 8]
- second: d[0]+=1 → [6, -3, 8]
- prefix 6, 3, 11
Result: a becomes [6, 3, 11]
same cell twice
a = [7], +4 on [0, 0] then +1 on [0, 0]- d[0]+=4 → 11
- d[0]+=1 → 12
Result: a becomes [12]
Try it
Write stackRangeAdds(d, updates). d is the difference array. Each update is (L, R, v): add v on inclusive [L, R]. Write every d[L] += v and d[R+1] -= v first. Rebuild once. Return a. [4, 1, 9] +2 on [0, 1] and +3 on [1, 2] → [6, 6, 12] [4, 1, 9] +1 on [0, 2] twice → [6, 3, 11] [7] +4 then +1 on [0, 0] → [12]
a is a non-empty array of integers. Each [L, R] satisfies 0 ≤ L ≤ R < n.