Arithmetic Progression Queries Given an integer array(ARR) of size N, the following operations need to be performed: update(l, r, val) : Add (val + i) to arr[l + i] where, 0 <= i <= r - l. rangeSum(l, r): return the sum of all elements in the array from index l to r, i.e., the sum of array arr[l...r]. Two type o...
The data structure we will use is Segment Tree with Lazy Propagation which is a quiet, efficient approach for doing for range updates. Our segment tree will store the sum of all segments of the array efficiently. Now,
For rangesum(l, r) operation, we will be performing the sum-query operation of the segment tree, which receives l and r as parameters where l denotes the left bound, and r denotes the right bound of the segment for which the sum is to be calculated.
For update(l, r, val) operation, as this is a range update operation so for this, we will use lazy-propagation: an advanced version of segment trees. We will build a lazy tree of type Pair containing two values ‘a’ and ‘d’, where ‘a’ denotes the first value of the series we need to update with, and ‘d’ denotes the common difference of the series. While updating each node in the segment tree, we will directly calculate the sum of the A.P series using the formula,
Sn = n2*(2 * a + (n - 1) * d),
Where n is the number of terms that need to be updated, so n equals the size of the segment for which the node is holding its sum (root node of the segment tree will hold the sum of the whole array, so its size equals the size of the array).
Space Complexity: O(1)Explanation:O(N), where N is the size of the input array.
In the worst case, we will be using two extra arrays of size 4*N to store and update values for the given array.
Time Complexity: O(1)Explanation:O(logN), per operation - where N is the size of the input array.
In the worst case, for each operation, we will be only going to the maximum depth of the segment tree or lazy tree from the root node.
Top JPMorgan Chase & Co. SDE-2 interview questions & answers
Popular interview questions of SDE-2
Reviews
Interviews
Salaries
Users/Month