![]() |
VOOZH | about |
Given an array containing n integers and a value d. m queries are given. Each query has two values start and end. For each query, the problem is to increment the values from the start to end index in the given array by the given value d. A linear time-efficient solution is required for handling such multiple queries.
Examples:
Input : arr[] = {3, 5, 4, 8, 6, 1}
Query list: {0, 3}, {4, 5}, {1, 4},
{0, 1}, {2, 5}
d = 2
Output : 7 11 10 14 12 5
Executing 1st query {0, 3}
arr = {5, 7, 6, 10, 6, 1}
Executing 2nd query {4, 5}
arr = {5, 7, 6, 10, 8, 3}
Executing 3rd query {1, 4}
arr = {5, 9, 8, 12, 10, 3}
Executing 4th query {0, 1}
arr = {7, 11, 8, 12, 10, 3}
Executing 5th query {2, 5}
arr = {7, 11, 10, 14, 12, 5}
Note: Each query is executed on the
previously modified array.
Naive Approach: For each query, traverse the array in the range start to end and increment the values in that range by the given value d.
Efficient Approach: Create an array sum[] of size n and initialize all of its index with the value 0. Now for each (start, end) index pair apply the given operation on the sum[] array. The operations are: sum[start] += d and sum[end+1] -= d only if the index (end+1) exists. Now, from the index i = 1 to n-1, accumulate the values in the sum[] array as: sum[i] += sum[i-1]. Finally for the index i = 0 to n-1, perform the operation: arr[i] += sum[i].
Implementation:
Original Array: 3 5 4 8 6 1 Modified Array: 7 11 10 14 12 5
Time Complexity: O(m+n)
Auxiliary Space: O(n)