Kth Largest Element in an Array
Last Updated :
18 Sep, 2024
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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In 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
4 min read
Sorting Algorithms A 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