Data Structures19 sections · 729 units
Open in Course

Range Update Point Query

Flipping the problem

Standard BIT: point update, prefix query.

What if you need: range update, point query?

Use a difference array with BIT! Let diff[i] = arr[i] - arr[i-1]. Then:

  • arr[i] = prefix(diff, i). Point query becomes prefix sum
  • To add δ\delta to range [l,r][l, r]: add δ\delta to diff[l], add δ-\delta to diff[r+1]
def rangeAdd(l, r, delta):
    update(l, delta)       # diff[l] += delta
    update(r + 1, -delta)  # diff[r+1] -= delta

def pointQuery(i):
    return prefix(i)  # sum of differences = arr[i]

You get O(logn)O(\log n) range update and O(logn)O(\log n) point query.