Skip to content
Related Articles

Related Articles

Given an array and two integers l and r, find the kth largest element in the range [l, r]
  • Difficulty Level : Expert
  • Last Updated : 08 Apr, 2019

Given an unsorted array arr[] of n integers and an integer k, the task is to find the kth largest element in the given index range [l, r]

Examples:

Input: arr[] = {5, 3, 2, 4, 1}, k = 4, l = 1, r = 5
Output: 4
4 will be the 4th element when arr[0…4] is sorted.

Input: arr[] = {1, 4, 2, 3, 5, 7, 6}, k = 3, l = 3, r = 6
Output: 5

Approach: A naive solution will be to sort the elements in the range and get the kth largest element, the time complexity of that solution will be nlog(n) for every query. We can solve each query in log(n) by using prefix array and binary search. All we have to do is maintain a 2d prefix array in which the ith row will contain number of elements less than equal to i in the same range as in the given array. After the prefix array is done all we need to do is a simple binary search over the prefix array. Hence the time complexity is drastically reduced.



Below is the implementation of the above approach:

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define MAX 1001
static int prefix[MAX][MAX];
int ar[MAX];
  
// Function to calculate the prefix
void cal_prefix(int n, int arr[])
{
    int i, j;
  
    // Creating one based indexing
    for (i = 0; i < n; i++)
        ar[i + 1] = arr[i];
  
    // Initilizing and creating prefix array
    for (i = 1; i <= 1000; i++) {
        for (j = 0; j <= n; j++)
            prefix[i][j] = 0;
  
        for (j = 1; j <= n; j++) {
  
            // Creating a prefix array for every
            // possible value in a given range
            prefix[i][j] = prefix[i][j - 1]
                           + (int)(ar[j] <= i ? 1 : 0);
        }
    }
}
  
// Function to return the kth largest element
// in the index range [l, r]
int ksub(int l, int r, int n, int k)
{
    int lo, hi, mid;
  
    lo = 1;
    hi = 1000;
  
    // Binary searching through the 2d array
    // and only checking the range in which
    // the sub array is a part
    while (lo + 1 < hi) {
        mid = (lo + hi) / 2;
        if (prefix[mid][r] - prefix[mid][l - 1] >= k)
            hi = mid;
        else
            lo = mid + 1;
    }
  
    if (prefix[lo][r] - prefix[lo][l - 1] >= k)
        hi = lo;
  
    return hi;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 4, 2, 3, 5, 7, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 4;
  
    // Creating the prefix array
    // for the given array
    cal_prefix(n, arr);
  
    // Queries
    int queries[][3] = { { 1, n, 1 },
                         { 2, n - 2, 2 },
                         { 3, n - 1, 3 } };
    int q = sizeof(queries) / sizeof(queries[0]);
  
    // Perform queries
    for (int i = 0; i < q; i++)
        cout << ksub(queries[i][0], queries[i][1],
                     n, queries[i][2])
             << endl;
  
    return 0;
}

Java




// Java implementation of the approach
import java.util.*;
  
class GFG
{
      
static int MAX = 1001;
static int prefix[][] = new int[MAX][MAX];
static int ar[] = new int[MAX];
  
// Function to calculate the prefix
static void cal_prefix(int n, int arr[])
{
    int i, j;
  
    // Creating one based indexing
    for (i = 0; i < n; i++)
        ar[i + 1] = arr[i];
  
    // Initilizing and creating prefix array
    for (i = 1; i <= 1000; i++) 
    {
        for (j = 0; j <= n; j++)
            prefix[i][j] = 0;
  
        for (j = 1; j <= n; j++) 
        {
  
            // Creating a prefix array for every
            // possible value in a given range
            prefix[i][j] = prefix[i][j - 1]
                        + (int)(ar[j] <= i ? 1 : 0);
        }
    }
}
  
// Function to return the kth largest element
// in the index range [l, r]
static int ksub(int l, int r, int n, int k)
{
    int lo, hi, mid;
  
    lo = 1;
    hi = 1000;
  
    // Binary searching through the 2d array
    // and only checking the range in which
    // the sub array is a part
    while (lo + 1 < hi) 
    {
        mid = (lo + hi) / 2;
        if (prefix[mid][r] - prefix[mid][l - 1] >= k)
            hi = mid;
        else
            lo = mid + 1;
    }
  
    if (prefix[lo][r] - prefix[lo][l - 1] >= k)
        hi = lo;
  
    return hi;
}
  
// Driver code
public static void main(String args[])
{
    int arr[] = { 1, 4, 2, 3, 5, 7, 6 };
    int n = arr.length;
    int k = 4;
  
    // Creating the prefix array
    // for the given array
    cal_prefix(n, arr);
  
    // Queries
    int queries[][] = { { 1, n, 1 },
                        { 2, n - 2, 2 },
                        { 3, n - 1, 3 } };
    int q = queries.length;
  
    // Perform queries
    for (int i = 0; i < q; i++)
        System.out.println( ksub(queries[i][0], queries[i][1],
                    n, queries[i][2]));
}
}
  
// This code is contributed by Arnab Kundu

Python3




# Python3 implementation of the approach
  
MAX = 1001
prefix = [[0 for i in range(MAX)] 
             for j in range(MAX)]
ar = [0 for i in range(MAX)]
  
# Function to calculate the prefix
def cal_prefix(n, arr):
      
    # Creating one based indexing
    for i in range(n):
        ar[i + 1] = arr[i]
  
    # Initilizing and creating prefix array
    for i in range(1, 1001, 1):
        for j in range(n + 1):
            prefix[i][j] = 0
  
        for j in range(1, n + 1):
              
            # Creating a prefix array for every
            # possible value in a given range
            if ar[j] <= i:
                k = 1
            else:
                k = 0
            prefix[i][j] = prefix[i][j - 1] + k
  
# Function to return the kth largest element
# in the index range [l, r]
def ksub(l, r, n, k):
    lo = 1
    hi = 1000
  
    # Binary searching through the 2d array
    # and only checking the range in which
    # the sub array is a part
    while (lo + 1 < hi):
        mid = int((lo + hi) / 2)
        if (prefix[mid][r] - 
            prefix[mid][l - 1] >= k):
            hi = mid
        else:
            lo = mid + 1
  
    if (prefix[lo][r] - 
        prefix[lo][l - 1] >= k):
        hi = lo
  
    return hi
  
# Driver code
if __name__ == '__main__':
    arr = [1, 4, 2, 3, 5, 7, 6]
    n = len(arr)
    k = 4
  
    # Creating the prefix array
    # for the given array
    cal_prefix(n, arr)
  
    # Queries
    queries = [[1, n, 1],
               [2, n - 2, 2],
               [3, n - 1, 3]]
    q = len(queries)
  
    # Perform queries
    for i in range(q):
        print(ksub(queries[i][0], 
                   queries[i][1], n, queries[i][2]))
          
# This code is contributed by
# Surendra_Gangwar

C#




// C# implementation of the approach
using System;
  
class GFG
{
      
static int MAX = 1001;
static int[,] prefix = new int[MAX,MAX];
static int[] ar = new int[MAX];
  
// Function to calculate the prefix
static void cal_prefix(int n, int[] arr)
{
    int i, j;
  
    // Creating one based indexing
    for (i = 0; i < n; i++)
        ar[i + 1] = arr[i];
  
    // Initilizing and creating prefix array
    for (i = 1; i <= 1000; i++) 
    {
        for (j = 0; j <= n; j++)
            prefix[i, j] = 0;
  
        for (j = 1; j <= n; j++) 
        {
  
            // Creating a prefix array for every
            // possible value in a given range
            prefix[i, j] = prefix[i, j - 1]
                        + (int)(ar[j] <= i ? 1 : 0);
        }
    }
}
  
// Function to return the kth largest element
// in the index range [l, r]
static int ksub(int l, int r, int n, int k)
{
    int lo, hi, mid;
  
    lo = 1;
    hi = 1000;
  
    // Binary searching through the 2d array
    // and only checking the range in which
    // the sub array is a part
    while (lo + 1 < hi) 
    {
        mid = (lo + hi) / 2;
        if (prefix[mid, r] - prefix[mid, l - 1] >= k)
            hi = mid;
        else
            lo = mid + 1;
    }
  
    if (prefix[lo, r] - prefix[lo, l - 1] >= k)
        hi = lo;
  
    return hi;
}
  
// Driver code
static void Main()
{
    int []arr = { 1, 4, 2, 3, 5, 7, 6 };
    int n = arr.Length;
    //int k = 4;
  
    // Creating the prefix array
    // for the given array
    cal_prefix(n, arr);
  
    // Queries
    int [,]queries = { { 1, n, 1 },
                        { 2, n - 2, 2 },
                        { 3, n - 1, 3 } };
    int q = queries.Length/queries.Rank-1;
  
    // Perform queries
    for (int i = 0; i < q; i++)
        Console.WriteLine( ksub(queries[i,0], queries[i,1],
                    n, queries[i, 2]));
}
}
  
// This code is contributed by mits

PHP




<?php
// PHP implementation of the approach
$MAX = 101;
$prefix = array_fill(0, $MAX, array_fill(0, $MAX, 0));
$ar = array_fill(0, $MAX, 0);
  
// Function to calculate the prefix
function cal_prefix($n, $arr)
{
    global $prefix,$ar,$MAX;
      
    // Creating one based indexing
    for ($i = 0; $i < $n; $i++)
        $ar[$i + 1] = $arr[$i];
  
    // Initilizing and creating prefix array
    for ($i = 1; $i <$MAX; $i++)
    {
        for ($j = 0; $j <= $n; $j++)
            $prefix[$i][$j] = 0;
  
        for ($j = 1; $j <= $n; $j++)
        {
  
            // Creating a prefix array for every
            // possible value in a given range
            $prefix[$i][$j] = $prefix[$i][$j - 1]
                        + (int)($ar[$j] <= $i ? 1 : 0);
        }
    }
}
  
// Function to return the kth largest element
// in the index range [l, r]
function ksub($l, $r, $n, $k)
{
    global $prefix, $ar, $MAX;
    $lo = 1;
    $hi = $MAX-1;
  
    // Binary searching through the 2d array
    // and only checking the range in which
    // the sub array is a part
    while ($lo + 1 < $hi
    {
        $mid = (int)(($lo + $hi) / 2);
        if ($prefix[$mid][$r] - $prefix[$mid][$l - 1] >= $k)
            $hi = $mid;
        else
            $lo = $mid + 1;
    }
  
    if ($prefix[$lo][$r] - $prefix[$lo][$l - 1] >= $k)
        $hi = $lo;
  
    return $hi;
}
  
    // Driver code
    $arr = array( 1, 4, 2, 3, 5, 7, 6 );
    $n = count($arr);
    $k = 4;
  
    // Creating the prefix array
    // for the given array
    cal_prefix($n, $arr);
  
    // Queries
    $queries = array(array( 1, $n, 1 ),
                        array( 2, $n - 2, 2 ),
                        array( 3, $n - 1, 3 ));
    $q = count($queries);
  
    // Perform queries
    for ($i = 0; $i < $q; $i++)
        echo ksub($queries[$i][0], $queries[$i][1],$n, $queries[$i][2])."\n";
  
    // This code is contributed by mits
?>
Output:
1
3
5

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live and Geeks Classes Live USA

My Personal Notes arrow_drop_up
Recommended Articles
Page :