Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
How to Find Largest Number in an Array in C++?
Next article icon

Given an array and two integers l and r, find the kth largest element in the range [l, r]

Last Updated : 08 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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];
 
    // Initializing 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];
 
    // Initializing 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]
 
    # Initializing 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];
 
    // Initializing 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];
 
    // Initializing 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
?>
 
 

Javascript




<script>
// Javascript implementation of the approach
let MAX = 101;
let prefix = new Array(MAX);
 
for (let i = 0; i < MAX; i++) {
    prefix[i] = new Array(MAX).fill(0)
}
 
let ar = new Array(MAX).fill(0);
 
// Function to calculate the prefix
function cal_prefix(n, arr) {
 
    // Creating one based indexing
    for (let i = 0; i < n; i++)
        ar[i + 1] = arr[i];
 
    // Initializing and creating prefix array
    for (let i = 1; i < MAX; i++) {
        for (let j = 0; j <= n; j++)
            prefix[i][j] = 0;
 
        for (let j = 1; j <= n; j++) {
 
            // Creating a prefix array for every
            // possible value in a given range
            prefix[i][j] = prefix[i][j - 1]
                + (ar[j] <= i ? 1 : 0);
        }
    }
}
 
// Function to return the kth largest element
// in the index range [l, r]
function ksub(l, r, n, k) {
    let lo = 1;
    let 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) {
        let mid = Math.floor((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
let arr = new Array(1, 4, 2, 3, 5, 7, 6);
let n = arr.length;
let k = 4;
 
// Creating the prefix array
// for the given array
cal_prefix(n, arr);
 
// Queries
let queries = new Array(new Array(1, n, 1),
    new Array(2, n - 2, 2),
    new Array(3, n - 1, 3));
let q = queries.length;
 
// Perform queries
for (let i = 0; i < q; i++)
    document.write(ksub(queries[i][0], queries[i][1], n, queries[i][2]) + "<br>");
 
// This code is contributed by _saurabh_jaiswal
</script>
 
 
Output: 
1 3 5

 

Time Complexity : O(n + q*log(MAX)) ,where n is the size of the array, q is the number of queries and MAX is the number of rows or columns of 2D prefix array.                                                                

Space Complexity : O(MAX*MAX) , to store elements in prefix matrix.



Next Article
How to Find Largest Number in an Array in C++?

R

Rafiu Jaman Mollah
Improve
Article Tags :
  • C++ Programs
  • DSA
  • Searching
Practice Tags :
  • Searching

Similar Reads

  • C++ Program to Find the Second Largest Element in an Array
    In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the second largest element in an array in C++. Examples: Input: arr[] = {34, 5, 16, 14, 56, 7, 56} Output: 34 Explanation: The
    3 min read
  • C++ Program to Find Largest Element in an Array
    In this article, we will learn to write a C++ program to find the largest element in the given array arr of size N. The element that is greater than all other elements is the largest element in the array. Recommended PracticeHelp a Thief!!!Try It! One of the most simplest and basic approaches to fin
    2 min read
  • Length of longest subarray for each index in Array where element at that index is largest
    Given an array arr[] of size N, the task is to calculate, for i(0<=i<N), the maximum length of a subarray containing arr[i], where arr[i] is the maximum element. Example: Input : arr[ ] = {62, 97, 49, 59, 54, 92, 21}, N=7Output: 1 7 1 3 1 5 1Explanation: The maximum length of subarray in which
    15 min read
  • Maximize the rightmost element of an array in k operations in Linear Time
    Given an array arr[ ] of size N and an integer p, the task is to find maximum possible value of rightmost element of array arr[ ] performing at most k operations.In one operation decrease arr[i] by p and increase arr[i+1] by p. Examples: Input: N = 4, p = 2, k = 5, arr = {3, 8, 1, 4}Output: 8Explana
    9 min read
  • How to Find Largest Number in an Array in C++?
    In C++, arrays are used to store the collection of similar elements to be stored in adjacent memory locations. They can store data of any type such as int, char, float, etc. In this article, we will learn how to find the largest number in an array in C++. For Example,Input: myVector = {1, 3, 10, 7,
    2 min read
  • How to Find the Maximum Element of an Array using STL in C++?
    Given an array of n elements, the task is to find the maximum element using STL in C++. Examples Input: arr[] = {11, 13, 21, 45, 8}Output: 45Explanation: 45 is the largest element of the array. Input: arr[] = {1, 9, 2, 5, 7}Output: 9Explanation: 9 is the largest element of the array. STL provides th
    3 min read
  • C++ Program for Third largest element in an array of distinct elements
    Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example :   Input: arr[] = {1, 14, 2, 16, 10, 20} Output: The third Largest element is 14 Explanation: Largest element is 20, second largest element is 16 and third largest element is 1
    5 min read
  • C++ Program to Find k maximum elements of array in original order
    Given an array arr[] and an integer k, we need to print k maximum elements of given array. The elements should printed in the order of the input.Note : k is always less than or equal to n. Examples: Input : arr[] = {10 50 30 60 15} k = 2 Output : 50 60 The top 2 elements are printed as per their app
    3 min read
  • Largest sub-set possible for an array satisfying the given condition
    Given an array arr[] and an integer K. The task is to find the size of the maximum sub-set such that every pair from the sub-set (X, Y) is of the form Y != (X * K) where X < Y. Examples: Input: arr[] = {2, 3, 6, 5, 4, 10}, K = 2 Output: 3 {2, 3, 5} is the required sub-set Input: arr[] = {1, 2, 3,
    5 min read
  • Maximum sum of pairs that are at least K distance apart in an array
    Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum sum of pairs of elements that are separated by at least K indices. Examples: Input: arr[] = {2, 4, 1, 6, 8}, K = 2Output: 12Explanation:The elements {1, 4} are K(= 2) distance apart. The sum of pairs {4,
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences