avik26091998's blog

By avik26091998, history, 7 years ago, In English

Can anybody explain me the concept of difference array??

  • Vote: I like it
  • +6
  • Vote: I do not like it

»
7 years ago, # |
  Vote: I like it +6 Vote: I do not like it

given an array A[n], its difference array D is some array that satisfies D[i] = A[i] — A[i — 1] (for 1 < i <= N), and D[1] = A[1].

It can be used to perform range update queries of, for instance, adding some value x to all indicies from l to r. you create the difference array, then for each query "l r x", you perform D[l] += x, D[r + 1] -= x, and after all the queries you return to the normal array from it, by performing partial sum (A[1] = D[1], A[i] = A[i — 1] + D[i]) and you're done. Each query was in O(1) instead of O(N).