Kth Largest Element in an Array
Last Updated :
27 Jul, 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
[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<int> &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<int> 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:
- If the size of the heap exceeds K, we remove the smallest element. This ensures that the heap maintains only the K largest elements.
- By the end of the process, the top element of the min-heap (which is the smallest of the K largest elements) will be the k-th largest element in the array.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the kth largest array element
int kthLargest(vector<int> 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:
- Pick a random pivot from the array.
- Partitioning the array into three parts:
- leftArr: Elements greater than the pivot.
- midArr: Elements equal to the pivot.
- rightArr: Elements less than the pivot.
- Check if k is smaller than or equal to size of leftArr then search into leftArr.
- If k is greater than size of leftArr + size of midArr then adjust k and search into rightArr.
- Otherwise, return the pivot (it’s the k-th largest element)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to perform quick select
int quickSelect(vector<int> &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<int> &arr, int k){
// Call quickSelect to find k-th largest
return quickSelect(arr, k);
}
int main(){
vector<int> 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<int>& 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<int> 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:
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem