![]() |
VOOZH | about |
Given an array arr of size N. The task is to find the kth smallest element in the subarray(l to r, both inclusive).
Note :
Examples:
Input : arr = {3, 2, 5, 4, 7, 1, 9}, query = (2, 6, 3)
Output : 4
sorted subarray in a range 2 to 6 is {1, 2, 4, 5, 7} and 3rd element is 4Input : arr = {2, 3, 4, 1, 6, 5, 8}, query = (1, 5, 2)
Output : 2
Let, S = r - l + 1.
Naive Approach:
Efficient Approach: The idea is to use Segment trees, to be more precise use merge sort segment tree. Here, Instead of storing sorted elements we store indexes of sorted elements.
Let B is the array after sorting arr and seg is our segment tree. Node ci of seg stores the sorted order of indices of arr which are in range [st, end].
If arr = {3, 1, 5, 2, 4, 7, 8, 6},
then B is {1, 2, 3, 4, 5, 6, 7, 8}
Segment tree will look like :
Let's suppose seg[ci]->left holds p elements. If p is less than or equals to k, we can find kth smallest in left child and if p is less than k then move to right child and find (k-p) smallest element.
One can find the number of elements in the sorted array(A) lying in between elements X and Y by:
upper_bound(A.begin(), A.end(), Y)-lower_bound(A.begin(), A.end(), X)
Below is the implementation of the above approach:
3rd smallest element in range 3 to 7 is: 5
Time complexity:
To build segment tree: O(n*log(n))
For each query : O(log(n)*log(n))
Auxiliary Space: O(n+N) where N=1e5