![]() |
VOOZH | about |
Given an array arr[] of N elements and a number of queries where each query will contain three integers L, R, and K. For each query, the task is to find the number of elements in the subarray arr[L...R] which are greater than K.
Examples:
Input: arr[] = {7, 3, 9, 13, 5, 4}, q[] = {{0, 3, 6}, {1, 5, 8}}
Output:
3
2
Query 1: Only 7, 9 and 13 are greater
than 6 in the subarray {7, 3, 9, 13}.
Query 2: Only 9 and 13 are greater
than 8 in the subarray {3, 9, 13, 5, 4}.
Input: arr[] = {0, 1, 2, 3, 4, 5, 6, 7}, q[] = {{0, 7, 3}, {4, 6, 10}}
Output:
4
0
Prerequisite:Segment tree
Naive approach: Find the answer for each query by simply traversing the array from index l till r and keep adding 1 to the count whenever the array element is greater than k.
Below is the implementation of the above approach:
Output:
3
2
Time Complexity: O(n * q)
Space Complexity: O(1)
Efficient approach: Build a Segment Tree with a vector at each node containing all the elements of the sub-range in sorted order. Answer each query using the segment tree where Binary Search can be used to calculate how many numbers are present in each node whose sub-range lies within the query range which is greater than K. Time complexity of this approach will be O(q * log(n) * log(n))
Below is the implementation of the above approach:
3 2
The space complexity of the segment tree is O(n log n). The tree has at most 4n nodes, and each node stores a vector of size at most n, which leads to the space complexity of O(n log n).
Another Approach:
Another way of doing it using segment trees is by storing the first element greater than K in each node (if present) in that range, otherwise storing 0.
Here, we need to consider 3 cases for building the tree.
The query function remains the same as always.
Consider the following example: arr[] = {7, 3, 9, 13, 5, 4} , K = 6
The tree in this case will look like this:
Below is the implementation of the above approach:
Output:
7
Time Complexity: O(N * log N) to build the tree and O(log N) for each query.
Space Complexity: O(N)