![]() |
VOOZH | about |
Given an array arr[] of size N and a matrix Q consisting of queries of the following two types:
Examples:
Input: arr[] = {1, 2, 2, 3, 4, 4, 5, 6}, Q = {{1, {3, 5}}, {1, {2, 4}}, {1, {1, 2}}, {2, {1, 7}}, {1, {1, 2}}}
Output: 4 5 3 2
Explanation:
Array elements from the range [3, 5] are {3, 4, 4, 5}
Array elements from the range [2, 4] are {2, 2, 3, 4, 4}
Array elements from the range [1, 2] are {1, 2, 2}
Replacing arr[1] by 7 modifies the array to {1, 7, 2, 3, 4, 4, 5, 6}
Elements that lie in range [1, 2] are {1, 2}Input: arr = {5, 5, 1, 3, 4, 4, 2, 3}, Q = {{1, {3, 6}}, {1, {2, 4}}, {1, {10, 20}}}
Output: 6 5 0
Explanation:
Array elements from the range [3, 6] are {3, 3, 4, 4, 5, 5}
Array elements from the range [2, 4] are {2, 3, 3, 4, 4}
No element from the range [10, 20] exists in the array.
Naive Approach:
The simplest approach to solve this problem is as follows:
Below is the implementation of the above approach:
4 5 3 2
Time Complexity: O(Q * N)
Auxiliary Space: O(1)
Efficient Approach:
The above approach can be optimized using Fenwick Tree. Follow the steps below to solve the problem:
getSum(R) – getSum(L - 1)
Below is the implementation of the above approach:
4 5 3 2
Time Complexity: O(n*log(N) + Q*log(N))
Auxiliary Space: O(maxm), where maxm is the maximum element present in the array.