In the previous post, we discussed range update and point query solutions using BIT.
rangeUpdate(l, r, val) : We add ‘val’ to element at index ‘l’. We subtract ‘val’ from element at index ‘r+1’.
getElement(index) [or getSum()]: We return sum of elements from 0 to index which can be quickly obtained using BIT.

A Simple Solution is to use solutions discussed in previous post. Range update query is same. Range sum query can be achieved by doing get query for all elements in range.

An Efficient Solution is to make sure that both queries can be done in O(Log n) time. We get range sum using prefix sums. How to make sure that update is done in a way so that prefix sum can be done quickly? Consider a situation where prefix sum [0, k] (where 0 <= k < n) is needed after range update on range [l, r]. Three cases arises as k can possibly lie in 3 regions.

How to get this result?
Simply add the val from lth index to kth index. Sum is incremented by “val*(k) – val*(l-1)” after update query.

Case 3: k > r
For this case, we need to add “val” from lth index to rth index. Sum is incremented by “val*r – val*(l-1)” due to update query.

Observations :Case 1: is simple as sum would remain same as it was before update.

Case 2: Sum was incremented by val*k – val*(l-1). We can find “val”, it is similar to finding the ith element in range update and point query article. So we maintain one BIT for Range Update and Point Queries, this BIT will be helpful in finding the value at kth index. Now val * k is computed, how to handle extra term val*(l-1)?
In order to handle this extra term, we maintain another BIT (BIT2). Update val * (l-1) at lth index, so when getSum query is performed on BIT2 will give result as val*(l-1).

Case 3 : The sum in case 3 was incremented by “val*r – val *(l-1)”, the value of this term can be obtained using BIT2. Instead of adding, we subtract “val*(l-1) – val*r” as we can get this value from BIT2 by adding val*(l-1) as we did in case 2 and subtracting val*r in every update operation.

This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.