VOOZH about

URL: https://www.geeksforgeeks.org/dsa/kth-smallest-element-in-a-subarray/

⇱ Kth smallest element in a subarray - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Kth smallest element in a subarray

Last Updated : 12 Jul, 2025

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 : 

  • Query are of type query(l, r, k)
  • 1 <= k <= r-l+1
  • There can be multiple queries.

Examples:  

Input : arr = {3, 2, 5, 4, 7, 1, 9}, query = (2, 6, 3) 
Output :
sorted subarray in a range 2 to 6 is {1, 2, 4, 5, 7} and 3rd element is 4

Input : arr = {2, 3, 4, 1, 6, 5, 8}, query = (1, 5, 2) 
Output : 2

Let, S = r - l + 1.

Naive Approach:  

  • Copy the subarray into some other local array. After sorting find the kth element. 
    Time complexity: Slog(S)
  • Use a max priority queue 'p' and iterate in the subarray. If size of 'p' is less than 'k' insert element else remove top element and insert the new element into 'p' after complete interaction top of 'p' will be the answer.
    Time complexity: Slog(k)

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 : 

👁 Image


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:  


Output: 
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
 

Comment
Article Tags: