Kth Largest Element in an Array (original) (raw)

Last Updated : 29 Oct, 2025

Given an integer array arr[] of size **n elements and a positive integer **K, the task is to return the kth largest element in the given array (not the Kth distinct element).

**Examples:

**Input: [1, 23, 12, 9, 30, 2, 50], K = 3
**Output: 23

**Input: [12, 3, 5, 7, 19], K = 2
**Output: 12

Table of Content

[Naive Approach] Using Sorting - O(n log(n)) time and O(1) space

The very basic approach is to sort the given array in descending order and return the element at the index **K - 1 (zero-based indexing).

C++ `

#include <bits/stdc++.h> using namespace std;

// Function to return K'th largest element int kthLargest(vector &arr, int K) {

// Sort the array in descending order
sort(arr.begin(), arr.end(), greater<int>());

// Return K'th largest element
return arr[K - 1];

}

int main() { vector arr = {12, 3, 5, 7, 19}; int K = 2; cout << kthLargest(arr, K); return 0; }

C

#include <stdio.h> #include <stdlib.h>

// Comparison function for qsort in descending order int compare(const void *a, const void b) { return ((int *)b - *(int *)a); }

// Function to find K'th largest element int kthLargest(int arr[], int n, int K) {

// Sort the array in descending order
qsort(arr, n, sizeof(int), compare);

// Return K'th largest element
return arr[K - 1];

}

int main() { int arr[] = {12, 3, 5, 7, 19}; int n = 5, K = 2; printf("%d", kthLargest(arr, n, K)); return 0; }

Java

import java.util.Arrays; import java.util.Collections;

class GfG {

// Function to return K'th largest element
static int kthLargest(Integer[] arr, int K) {
  
    // Sort the array in descending order
    Arrays.sort(arr, Collections.reverseOrder());
  
    // Return K'th largest element
    return arr[K - 1];
}

public static void main(String[] args) {
    Integer[] arr = {12, 3, 5, 7, 19};
    int K = 2;
    System.out.println(kthLargest(arr, K));
}

}

Python

Function to return K'th largest element

def kth_largest(arr, K):

# Sort the array in descending order
arr.sort(reverse=True)

# Return K'th largest element
return arr[K - 1]

arr = [12, 3, 5, 7, 19] K = 2 print(kth_largest(arr, K))

C#

using System; using System.Linq;

class GfG {

// Function to return K'th largest element
static int KthLargest(int[] arr, int K) {
  
    // Sort the array in descending order
    Array.Sort(arr);
    Array.Reverse(arr);
  
    // Return K'th largest element
    return arr[K - 1];
}

static void Main() {
    int[] arr = {12, 3, 5, 7, 19};
    int K = 2;
    Console.WriteLine(KthLargest(arr, K));
}

}

JavaScript

// Function to return K'th largest element function kthLargest(arr, K) {

// Sort the array in descending order
arr.sort((a, b) => b - a);

// Return K'th largest element
return arr[K - 1];

}

const arr = [12, 3, 5, 7, 19]; const K = 2; console.log(kthLargest(arr, K));

`

**Time Complexity: O(n log n)
**Auxiliary Space: O(1)

[Expected Approach**] Using Priority Queue(Min-Heap) - O(n * log(K)) time and O(K) space**

The idea is to maintain a **min-heap (priority queue) of size **K while iterating through the array. This approach ensures that the heap always contains the **K largest elements encountered so far. As we add elements to the heap:

C++ `

#include <bits/stdc++.h> using namespace std;

// Function to find the kth largest array element int kthLargest(vector arr, int K){ int n = arr.size();

// Create a min heap (priority queue)
priority_queue<int, vector<int>, greater<int>> pq;

// Iterate through the array elements
for (int i = 0; i < n; i++) {

    // Push the current element onto the min heap
    pq.push(arr[i]);

    // If the size of the min heap exceeds K,
    // remove the largest element
    if (pq.size() > K)
        pq.pop();
}

// Return the Kth largest element (top of the min heap)
return pq.top();

}

int main(){

vector<int> arr = { 12, 3, 5, 7, 19 };
int K = 2;

cout << kthLargest(arr, K);
return 0;

}

Java

import java.util.PriorityQueue;

class GfG {

// Function to find the K'th largest element
public static int kthLargest(int[] arr, int K) {
  
    // Min heap to store K largest elements
    PriorityQueue<Integer> pq = new PriorityQueue<>();
    
    // Iterate through the array elements
    for (int val : arr) {
      
        // Add current element to the min heap
        pq.add(val);
        // If heap exceeds size K, remove smallest element
        if (pq.size() > K)
            pq.poll();
    }

    // Top of the heap is the K'th largest element
    return pq.peek();
}

public static void main(String[] args) {
    int[] arr = {12, 3, 5, 7, 19};
    int K = 2;
    System.out.println(kthLargest(arr, K));
}

}

Python

import heapq

Function to find the K'th largest element

def kth_largest(arr, K):

# Min heap to store K largest elements
pq = []

# Iterate through the array elements
for val in arr:
  
    # Add current element to the min heap
    heapq.heappush(pq, val)
    
    # If heap exceeds size K, remove smallest element
    if len(pq) > K:
        heapq.heappop(pq)

# Top of the heap is the K'th largest element
return pq[0]

arr = [12, 3, 5, 7, 19] K = 2 print(kth_largest(arr, K))

C#

using System; using System.Collections.Generic;

class GfG {

// Function to find the K'th largest element
static int KthLargest(int[] arr, int K) {
  
    // Min heap to store K largest elements
    SortedSet<int> pq = new SortedSet<int>();

    // Iterate through the array elements
    foreach (int val in arr) {
      
        // Add current element to the min heap
        pq.Add(val);
      
        // If heap exceeds size K, remove smallest element
        if (pq.Count > K)
            pq.Remove(pq.Min);
    }

    // Return K'th largest element
    return pq.Min;
}

static void Main() {
    int[] arr = {12, 3, 5, 7, 19};
    int K = 2;
    Console.WriteLine(KthLargest(arr, K));
}

}

JavaScript

// Function to find the K'th largest element function kthLargest(arr, K) {

// Min heap to store K largest elements
let pq = [];

// Iterate through the array elements
arr.forEach((val) => {

    // Add current element to the min heap
    pq.push(val);
    pq.sort((a, b) => a - b);
    
    // If heap exceeds size K, remove smallest element
    if (pq.length > K) {
        pq.shift();
    }
});

// Return K'th largest element
return pq[0];

}

const arr = [12, 3, 5, 7, 19]; const K = 2; console.log(kthLargest(arr, K));

`

**Time Complexity: O(n * log(K)), Each insertion and removal operation in a heap takes O(log(K)), and we perform this operation n times for the array.
**Auxiliary Space: O(K), The heap stores at most K elements at a time.

**[QuickSelect] Works Best in Practice - O(n) on average time and O(n) space

This is an optimization over method 1, if **QuickSort is used as a sorting algorithm in first step. In QuickSort, pick a **pivot element, then move the **pivot element to its correct position and partition the surrounding array. The idea is, not to do complete quicksort, but stop at the point where **pivot itself is **k'th largest element. Also, not to recur for both **left and **right sides of pivot, but recur for one of them according to the position of pivot.

Step-by-step approach:

Below is the implementation of the above approach:

C++ `

#include <bits/stdc++.h> using namespace std;

// Function to perform quick select int quickSelect(vector &arr, int k){

// Randomly select a pivot index from the array
int pivotIdx = rand() % arr.size();

// Get the pivot value
int pivot = arr[pivotIdx]; 


// For keeping elements greater than the pivot
vector<int> leftArr; 

// For keeping elements equal to the pivot
vector<int> midArr; 

// For keeping elements less than the pivot
vector<int> rightArr; 

// Partitioning the array based on the pivot
for (int val : arr){
    if (val > pivot){
        leftArr.push_back(val); 
    }
    else if (val < pivot){
        rightArr.push_back(val); 
    }
    else{
        midArr.push_back(val); 
    }
}

// Recursive selection based on the size of the partitions
if (k <= leftArr.size()){

    // If k is in the left partition, recurse into it
    return quickSelect(leftArr, k);
}
if (leftArr.size() + midArr.size() < k){
    
    // If k is in the right partition, adjust k and recurse
    return quickSelect(rightArr, k - leftArr.size() 
                                         - midArr.size());
}

// If k is in the mid partition, return the pivot
return pivot;

}

// Wrapper function to find the k-th largest element int KthLargest(vector &arr, int k){

 // Call quickSelect to find k-th largest
return quickSelect(arr, k);

}

int main(){ vector arr = {12, 3, 5, 7, 19}; int k = 2; cout << KthLargest(arr, k);

return 0; 

}

Java

import java.util.ArrayList; import java.util.List; import java.util.Random;

class GfG {

// Function to perform quick select
static int quickSelect(List<Integer> arr, int k) {
    
    // Randomly select a pivot index
    int pivotIdx = new Random().nextInt(arr.size());

    // Get the pivot value
    int pivot = arr.get(pivotIdx);

    // For elements greater than the pivot
    List<Integer> leftArr = new ArrayList<>();

    // For elements equal to the pivot
    List<Integer> midArr = new ArrayList<>();

    // For elements less than the pivot
    List<Integer> rightArr = new ArrayList<>();

    // Partitioning the array based on the pivot
    for (int val : arr) {
        if (val > pivot) {
            leftArr.add(val);
        } else if (val < pivot) {
            rightArr.add(val);
        } else {
            midArr.add(val);
        }
    }

    // Recursive selection
    if (k <= leftArr.size()) {
        return quickSelect(leftArr, k);
    }
    if (leftArr.size() + midArr.size() < k) {
        return quickSelect(rightArr, k - leftArr.size() 
                                           - midArr.size());
    }

    // Return pivot as the k-th largest
    return pivot;
}

// Wrapper function to find the k-th largest
static int KthLargest(int[] arr, int k) {
    List<Integer> arrList = new ArrayList<>();
    for (int val : arr) {
        arrList.add(val);
    }
    return quickSelect(arrList, k);
}

public static void main(String[] args) {
    int[] arr = {12, 3, 5, 7, 19};
    int k = 2;
    System.out.println(KthLargest(arr, k));
}

}

Python

import random

Function to perform quick select

def quick_select(arr, k):

# Randomly select a pivot
pivot = random.choice(arr)

# For elements greater than the pivot
leftArr = [x for x in arr if x > pivot]

# For elements equal to the pivot
midArr = [x for x in arr if x == pivot]

# For elements less than the pivot
rightArr = [x for x in arr if x < pivot]

# Recursive selection
if k <= len(leftArr):
    return quick_select(leftArr, k)
if len(leftArr) + len(midArr) < k:
    return quick_select(rightArr, k - len(leftArr) - len(midArr))

# Return pivot as the k-th largest
return pivot

Wrapper function to find the k-th largest

def kth_largest(arr, k): return quick_select(arr, k)

if name == "main": arr = [12, 3, 5, 7, 19] k = 2 print(kth_largest(arr, k))

C#

using System; using System.Collections.Generic;

class GfG {

// Function to perform quick select
static int QuickSelect(List<int> arr, int k){

    // Randomly select a pivot index
    Random rand = new Random();
    int pivotIdx = rand.Next(arr.Count);
    int pivot = arr[pivotIdx];

    // For elements greater than the pivot
    List<int> leftArr = new List<int>();

    // For elements equal to the pivot
    List<int> midArr = new List<int>();

    // For elements less than the pivot
    List<int> rightArr = new List<int>();

    // Partitioning the array based on the pivot
    foreach(int val in arr){
        if (val > pivot) {
            leftArr.Add(val);
        }
        else if (val < pivot) {
            rightArr.Add(val);
        }
        else {
            midArr.Add(val);
        }
    }

    // Recursive selection
    if (k <= leftArr.Count) {
        return QuickSelect(leftArr, k);
    }
    if (leftArr.Count + midArr.Count < k) {
        return QuickSelect(
            rightArr, k - leftArr.Count - midArr.Count);
    }

    // Return pivot as the k-th largest
    return pivot;
}

// Wrapper function to find the k-th largest
static int KthLargest(int[] arr, int k){
    List<int> arrList = new List<int>(arr);
    return QuickSelect(arrList, k);
}

public static void Main(){
    int[] arr = { 12, 3, 5, 7, 19 };
    int k = 2;
    Console.WriteLine(KthLargest(arr, k));
}

}

JavaScript

function quickSelect(arr, k) { // Randomly select a pivot const pivot = arr[Math.floor(Math.random() * arr.length)];

// For elements greater than the pivot
const leftArr = arr.filter(x => x > pivot);

// For elements equal to the pivot
const midArr = arr.filter(x => x === pivot);

// For elements less than the pivot
const rightArr = arr.filter(x => x < pivot);

// Recursive selection
if (k <= leftArr.length) {
    return quickSelect(leftArr, k);
}
if (leftArr.length + midArr.length < k) {
    return quickSelect(rightArr, k - leftArr.length
                                     - midArr.length);
}

// Return pivot as the k-th largest
return pivot;

}

// Wrapper function to find the k-th largest function KthLargest(arr, k) { return quickSelect(arr, k); }

const arr = [ 12, 3, 5, 7, 19 ]; const k = 2; console.log(KthLargest(arr, k));

`

**Time Complexity: O(n) on average, O(n2) in the worst case
**Auxiliary Space: O(n)

[Other Approach] Using Counting Sort (Not efficient for large range of elements)

Lets suppose the range of the numbers is small and limited between **-10^5 and **10^5, then we can take the advantage to use counting sort, we can count the occurrences of each number in this range and then determine the k-th largest element by traversing the counts in reverse order (since we are interested in the largest elements).

C++ `

#include <bits/stdc++.h> using namespace std;

// Function to find the K-th largest element using counting sort int kthLargest(vector& arr, int K) {

// The range for -10^5 to 10^5
int range = 200010;
vector<int> freq(range, 0);

// Count the frequency of each number
for (int val : arr) {
    freq[val + 100000]++;
}

// Traverse the frequency array from the largest to smallest
int count = 0;
for (int i = range - 1; i >= 0; i--) {
    count += freq[i];

    // Once we reach the K-th largest, return the number
    if (count >= K) {

        // Convert back to the original value
        return i - 100000; 
    }
}

// In case K doesn't exist
return -1; 

}

int main() { vector arr = {12, 3, 5, 7, 19}; int K = 2;

cout << kthLargest(arr, K) << endl;
return 0;

}

C

#include <stdio.h>

int kthLargest(int arr[], int n, int K) {

// The range for -10^5 to 10^5
int range = 200010;
int freq[200010] = {0};

// Count the frequency of each number
for (int i = 0; i < n; i++) {
    freq[arr[i] + 100000]++;
}

// Traverse the frequency array from largest to smallest
int count = 0;
for (int i = range - 1; i >= 0; i--) {
    count += freq[i];

    // Return the k-th largest element
    if (count >= K) {
        return i - 100000;
    }
}

// In case K doesn't exist
return -1;

}

int main() { int arr[] = {12, 3, 5, 7, 19}; int n = sizeof(arr) / sizeof(arr[0]); int K = 2;

printf("%d\n", kthLargest(arr, n, K));
return 0;

}

Java

import java.util.*;

public class GfG {

static int kthLargest(int[] arr, int K) {

    // The range for -10^5 to 10^5
    int range = 200010;
    int[] freq = new int[range];

    // Count the frequency of each number
    for (int val : arr) {
        freq[val + 100000]++;
    }

    // Traverse the frequency array from largest to smallest
    int count = 0;
    for (int i = range - 1; i >= 0; i--) {
        count += freq[i];

        // Return the k-th largest element
        if (count >= K) {
            return i - 100000;
        }
    }

    // In case K doesn't exist
    return -1;
}

public static void main(String[] args) {
    int[] arr = {12, 3, 5, 7, 19};
    int K = 2;
    System.out.println(kthLargest(arr, K));
}

}

Python

def kth_largest(arr, K):

# The range for -10^5 to 10^5
range_size = 200010
freq = [0] * range_size

# Count the frequency of each number
for val in arr:
    freq[val + 100000] += 1

# Traverse the frequency array from largest to smallest
count = 0
for i in range(range_size - 1, -1, -1):
    count += freq[i]

    # Return the k-th largest element
    if count >= K:
        return i - 100000

# In case K doesn't exist
return -1

arr = [12, 3, 5, 7, 19] K = 2 print(kth_largest(arr, K))

C#

using System;

class GfG {

static int KthLargestElement(int[] arr, int K) {

    // The range for -10^5 to 10^5
    int range = 200010;
    int[] freq = new int[range];

    // Count the frequency of each number
    foreach (int val in arr) {
        freq[val + 100000]++;
    }

    // Traverse the frequency array from largest to smallest
    int count = 0;
    for (int i = range - 1; i >= 0; i--) {
        count += freq[i];

        // Return the k-th largest element
        if (count >= K) {
            return i - 100000;
        }
    }

    // In case K doesn't exist
    return -1;
}

static void Main() {
    int[] arr = { 12, 3, 5, 7, 19 };
    int K = 2;

    Console.WriteLine(KthLargestElement(arr, K));
}

}

JavaScript

function kthLargest(arr, K) {

// The range for -10^5 to 10^5
const range = 200010;
const freq = new Array(range).fill(0);

// Count the frequency of each number
arr.forEach(val => {
    freq[val + 100000]++;
});

// Traverse the frequency array from largest to smallest
let count = 0;
for (let i = range - 1; i >= 0; i--) {
    count += freq[i];

    // Return the k-th largest element
    if (count >= K) {
        return i - 100000;
    }
}

// In case K doesn't exist
return -1;

}

const arr = [12, 3, 5, 7, 19]; const K = 2; console.log(kthLargest(arr, K));

`

**Time Complexity: O(n + R), where **n is the size of the input array and **R is the size of the frequency array
**Auxiliary Space: O(R)

**Related Article: