![]() |
VOOZH | about |
Given an array arr[0..n-1]. The following operations need to be performed.
Initially all the elements in the array are 0. Queries can be in any order, i.e., there can be many updates before point query.
Example:
Input: arr = {0, 0, 0, 0, 0}
Queries: update : l = 0, r = 4, val = 2
getElement : i = 3
update : l = 3, r = 4, val = 3
getElement : i = 3
Output: Element at 3 is 2
Element at 3 is 5
Explanation: Array after first update becomes
{2, 2, 2, 2, 2}
Array after second update becomes
{2, 2, 2, 5, 5}Method 1 [update : O(n), getElement() : O(1)]
The time complexity in the worst case is O(q*n) where q is the number of queries and n is the number of elements.
Method 2 [update: O(1), getElement(): O(n)]
We can avoid updating all elements and can update only 2 indexes of the array!
arr[l] = arr[l] + val arr[r+1] = arr[r+1] - val
Let’s analyze the update query. Why to add val to lth index? Adding val to lth index means that all the elements after l are increased by val, since we will be computing the prefix sum for every element. Why to subtract val from (r+1)th index? A range update was required from [l,r] but what we have updated is [l, n-1] so we need to remove val from all the elements after r i.e., subtract val from (r+1)th index. Thus the val is added to range [l,r]. Below is the implementation of the above approach.
Output:
Element at index 4 is 2 Element at index 3 is 6
Time complexity : O(q*n) where q is number of queries.
Auxiliary Space: O(n)
Method 3 (Using Binary Indexed Tree)
In method 2, we have seen that the problem can reduced to update and prefix sum queries. We have seen that BIT can be used to do update and prefix sum queries in O(Logn) time. Below is the implementation.
Output:
Element at index 4 is 2 Element at index 3 is 6
Time Complexity : O(q * log n) + O(n * log n) where q is number of queries.
Auxiliary Space: O(n)
Method 1 is efficient when most of the queries are getElement(), method 2 is efficient when most of the queries are updates() and method 3 is preferred when there is mix of both queries.