Given an array arr[] of size N, the task is to printing K largest elements in an array.
Note: Elements in output array can be in any order
Examples:
Input: [1, 23, 12, 9, 30, 2, 50], K = 3
Output: 50, 30, 23
Input: [11, 5, 12, 9, 44, 17, 2], K = 2
Output: 44, 17
K largest elements in an array using Sorting:
Sort the input array in descending order so that the first K elements in the array are the K largest elements
Follow the below steps to solve the problem:
- Sort the elements in descending order
- Print the first K numbers of the sorted array
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void kLargest( int arr[], int n, int k)
{
sort(arr, arr + n, greater< int >());
for ( int i = 0; i < k; i++)
cout << arr[i] << " " ;
}
int main()
{
int arr[] = { 1, 23, 12, 9, 30, 2, 50 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
kLargest(arr, n, k);
}
|
C
#include <stdio.h>
#include <stdlib.h>
int cmpfunc( const void * a, const void * b)
{
return (*( int *)b - *( int *)a);
}
void kLargest( int arr[], int n, int k)
{
qsort (arr, n, sizeof ( int ), cmpfunc);
for ( int i = 0; i < k; i++)
printf ( "%d " , arr[i]);
}
int main()
{
int arr[] = { 1, 23, 12, 9, 30, 2, 50 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
kLargest(arr, n, k);
}
|
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
class GFG {
public static void kLargest(Integer[] arr, int k)
{
Arrays.sort(arr, Collections.reverseOrder());
for ( int i = 0 ; i < k; i++)
System.out.print(arr[i] + " " );
}
public static ArrayList<Integer> kLargest( int [] arr,
int k)
{
Integer[] obj_array
= Arrays.stream(arr).boxed().toArray(
Integer[] :: new );
Arrays.sort(obj_array, Collections.reverseOrder());
ArrayList<Integer> list = new ArrayList<>(k);
for ( int i = 0 ; i < k; i++)
list.add(obj_array[i]);
return list;
}
public static void main(String[] args)
{
Integer arr[]
= new Integer[] { 1 , 23 , 12 , 9 , 30 , 2 , 50 };
int k = 3 ;
kLargest(arr, k);
int [] prim_array = { 1 , 23 , 12 , 9 , 30 , 2 , 50 };
kLargest(prim_array, k);
}
}
|
Python
def kLargest(arr, k):
arr.sort(reverse = True )
for i in range (k):
print (arr[i], end = " " )
arr = [ 1 , 23 , 12 , 9 , 30 , 2 , 50 ]
k = 3
kLargest(arr, k)
|
C#
using System;
class GFG {
public static void kLargest( int [] arr, int k)
{
Array.Sort(arr);
Array.Reverse(arr);
for ( int i = 0; i < k; i++)
Console.Write(arr[i] + " " );
}
public static void Main(String[] args)
{
int [] arr = new int [] { 1, 23, 12, 9, 30, 2, 50 };
int k = 3;
kLargest(arr, k);
}
}
|
Javascript
<script>
function kLargest(arr, n, k)
{
arr.sort((a, b) => b - a);
for (let i = 0; i < k; i++)
document.write(arr[i] + " " );
}
let arr = [ 1, 23, 12, 9, 30, 2, 50 ];
let n = arr.length;
let k = 3;
kLargest(arr, n, k);
</script>
|
PHP
<?php
function kLargest(& $arr , $n , $k )
{
rsort( $arr );
for ( $i = 0; $i < $k ; $i ++)
echo $arr [ $i ] . " " ;
}
$arr = array (1, 23, 12, 9,
30, 2, 50);
$n = sizeof( $arr );
$k = 3;
kLargest( $arr , $n , $k );
?>
|
Time complexity: O(N * log(N))
Auxiliary Space: O(1)
K largest elements in an array using Binary Search:
The idea is to find the Kth largest element of the array and then print all the elements which are greater than or equal to Kth largest Element. The Kth largest element can be found using binary search by defining a search range based on the minimum and maximum values in the input array. In each iteration of binary search, count the larger than the midpoint and update the search range accordingly. This process continues until the range collapses to a single element, which is the kth largest element.
Follow the given steps to solve the problem:
- Initialize low and high to minimum and maximum element of the array denoting the range within which the answer lies.
- Apply Binary Search on this range.
- If the selected element by calculating mid has less than K elements lesser to it then increase the number that is low = mid + 1.
- Otherwise, Decrement the high pointer, i.e high = mid.
- The Binary Search will terminate when only one element remains in the answer space that would be the Kth largest element.
- Print all the elements which are greater than or equal to Kth largest element.
Below is the implementation of above approach:
C++
#include <algorithm>
#include <climits>
#include <iostream>
using namespace std;
int findKthLargest( int arr[], int n, int k)
{
int low = INT_MAX, high = INT_MIN;
for ( int i = 0; i < n; i++) {
low = min(low, arr[i]);
high = max(high, arr[i]);
}
while (low <= high) {
int mid = low + (high - low) / 2;
int count = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] > mid) {
count++;
}
}
if (count >= k) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return high;
}
void printKLargest( int arr[], int n, int k)
{
int kthLargest = findKthLargest(arr, n, k);
for ( int i = 0; i < n; i++) {
if (arr[i] >= kthLargest) {
cout << arr[i] << " " ;
}
}
cout << endl;
}
int main()
{
int arr[] = { 12, 5, 787, 1, 23 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 2;
cout << "K largest elements: " ;
printKLargest(arr, n, k);
return 0;
}
|
C#
using System;
namespace KthLargestElement
{
class Program
{
static int FindKthLargest( int [] arr, int n, int k)
{
int low = int .MaxValue;
int high = int .MinValue;
foreach ( int num in arr)
{
low = Math.Min(low, num);
high = Math.Max(high, num);
}
while (low <= high)
{
int mid = low + (high - low) / 2;
int count = 0;
foreach ( int num in arr)
{
if (num > mid)
{
count++;
}
}
if (count >= k)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return high;
}
static void PrintKLargest( int [] arr, int n, int k)
{
int kthLargest = FindKthLargest(arr, n, k);
foreach ( int num in arr)
{
if (num >= kthLargest)
{
Console.Write(num + " " );
}
}
Console.WriteLine();
}
static void Main( string [] args)
{
int [] arr = { 12, 5, 787, 1, 23 };
int n = arr.Length;
int k = 2;
Console.Write( "K largest elements: " );
PrintKLargest(arr, n, k);
}
}
}
|
OutputK largest elements: 787 23
Time complexity: O(n * log (mx-mn)), where mn be minimum and mx be maximum element of array.
Auxiliary Space: O(1)
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.
Follow the given steps to solve the problem:
- Run quick sort algorithm on the input array
- In this algorithm pick a pivot element and move it to it’s correct position
- Now, if index of pivot is equal to K then return , else if the index of pivot is less than K, then recur for the right subarray, else recur for the left subarray.
- Repeat this process until the element at index K is not found.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int partition( int arr[], int l, int r);
void KthLargest( int arr[], int l, int r, int K, int N)
{
int pos = partition(arr, l, r);
if (pos - l == K - 1)
return ;
else if (pos - l < K - 1)
return KthLargest(arr, pos + 1, r, K - pos + l - 1,
N);
else
return KthLargest(arr, l, pos - 1, K, N);
}
void swap( int * a, int * b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int partition( int arr[], int l, int r)
{
int x = arr[r], i = l;
for ( int j = l; j <= r - 1; j++) {
if (arr[j] <= x) {
swap(&arr[i], &arr[j]);
i++;
}
}
swap(&arr[i], &arr[r]);
return i;
}
int main()
{
int arr[]
= { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
int N = sizeof (arr) / sizeof (arr[0]);
int k = 3;
KthLargest(arr, 0, N - 1, k, N);
cout << k << " largest elements are : " ;
for ( int i = N - 1; i >= N - k; i--)
cout << arr[i] << " " ;
return 0;
}
|
C
#include <stdio.h>
void swap( int * a, int * b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition( int arr[], int l, int r) {
int x = arr[r], i = l;
for ( int j = l; j <= r - 1; j++) {
if (arr[j] <= x) {
swap(&arr[i], &arr[j]);
i++;
}
}
swap(&arr[i], &arr[r]);
return i;
}
void KthLargest( int arr[], int l, int r, int K, int N) {
int pos = partition(arr, l, r);
if (pos - l == K - 1)
return ;
else if (pos - l < K - 1)
return KthLargest(arr, pos + 1, r, K - pos + l - 1, N);
else
return KthLargest(arr, l, pos - 1, K, N);
}
int main() {
int arr[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
int N = sizeof (arr) / sizeof (arr[0]);
int k = 3;
KthLargest(arr, 0, N - 1, k, N);
printf ( "%d largest elements are: " , k);
for ( int i = N - 1; i >= N - k; i--)
printf ( "%d " , arr[i]);
printf ( "\n" );
return 0;
}
|
Java
public class KthLargestElements {
static void swap( int [] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
static int partition( int [] arr, int l, int r) {
int x = arr[r];
int i = l;
for ( int j = l; j <= r - 1 ; j++) {
if (arr[j] <= x) {
swap(arr, i, j);
i++;
}
}
swap(arr, i, r);
return i;
}
static void kthLargest( int [] arr, int l, int r, int k, int N) {
int pos = partition(arr, l, r);
if (pos - l == k - 1 )
return ;
else if (pos - l < k - 1 )
kthLargest(arr, pos + 1 , r, k - pos + l - 1 , N);
else
kthLargest(arr, l, pos - 1 , k, N);
}
public static void main(String[] args) {
int [] arr = { 11 , 3 , 2 , 1 , 15 , 5 , 4 , 45 , 88 , 96 , 50 , 45 };
int N = arr.length;
int k = 3 ;
kthLargest(arr, 0 , N - 1 , k, N);
System.out.print(k + " largest elements are: " );
for ( int i = N - 1 ; i >= N - k; i--)
System.out.print(arr[i] + " " );
System.out.println();
}
}
|
Python3
def partition(arr, l, r):
x = arr[r]
i = l
for j in range (l, r):
if arr[j] < = x:
arr[i], arr[j] = arr[j], arr[i]
i + = 1
arr[i], arr[r] = arr[r], arr[i]
return i
def kthLargest(arr, l, r, k, N):
pos = partition(arr, l, r)
if pos - l = = k - 1 :
return
elif pos - l < k - 1 :
kthLargest(arr, pos + 1 , r, k - pos + l - 1 , N)
else :
kthLargest(arr, l, pos - 1 , k, N)
if __name__ = = "__main__" :
arr = [ 11 , 3 , 2 , 1 , 15 , 5 , 4 , 45 , 88 , 96 , 50 , 45 ]
N = len (arr)
k = 3
kthLargest(arr, 0 , N - 1 , k, N)
print (f "{k} largest elements are:" , end = " " )
for i in range (N - 1 , N - k - 1 , - 1 ):
print (arr[i], end = " " )
print ()
|
C#
using System;
public class KthLargestElements
{
static void Swap( int [] arr, int a, int b)
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
static int Partition( int [] arr, int l, int r)
{
int x = arr[r];
int i = l;
for ( int j = l; j <= r - 1; j++)
{
if (arr[j] <= x)
{
Swap(arr, i, j);
i++;
}
}
Swap(arr, i, r);
return i;
}
static void KthLargest( int [] arr, int l, int r, int k, int N)
{
int pos = Partition(arr, l, r);
if (pos - l == k - 1)
return ;
else if (pos - l < k - 1)
KthLargest(arr, pos + 1, r, k - pos + l - 1, N);
else
KthLargest(arr, l, pos - 1, k, N);
}
public static void Main()
{
int [] arr = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
int N = arr.Length;
int k = 3;
KthLargest(arr, 0, N - 1, k, N);
Console.Write($ "{k} largest elements are: " );
for ( int i = N - 1; i >= N - k; i--)
Console.Write($ "{arr[i]} " );
Console.WriteLine();
}
}
|
Javascript
using System;
public class KthLargestElements
{
static void Swap(int[] arr, int a, int b)
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
static int Partition(int[] arr, int l, int r)
{
int x = arr[r];
int i = l;
for (int j = l; j <= r - 1; j++)
{
if (arr[j] <= x)
{
Swap(arr, i, j);
i++;
}
}
Swap(arr, i, r);
return i;
}
static void KthLargest(int[] arr, int l, int r, int k, int N)
{
int pos = Partition(arr, l, r);
if (pos - l == k - 1)
return ;
else if (pos - l < k - 1)
KthLargest(arr, pos + 1, r, k - pos + l - 1, N);
else
KthLargest(arr, l, pos - 1, k, N);
}
public static void Main()
{
int[] arr = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
int N = arr.Length;
int k = 3;
KthLargest(arr, 0, N - 1, k, N);
Console.Write($ "{k} largest elements are: " );
for (int i = N - 1; i >= N - k; i--)
Console.Write($ "{arr[i]} " );
Console.WriteLine();
}
}
|
Output3 largest elements are : 88 50 96
Time Complexity: O(N2) in worst case(O(N) on average).
Auxiliary Space: O(N)
Note: We can improve on the standard quicksort algorithm by using the random() function. Instead of using the pivot element as the last element, we can randomly choose the pivot element randomly.
The intuition behind this approach is to maintain a minheap (priority queue) of size K while iterating through the array. Doing this ensures that the min heap always contains the K largest elements encountered so far. If the size of the min heap exceeds K, remove the smallest element this step ensures that the heap maintains the K largest elements encountered so far. In the end, the min heap contains the K largest elements of the array.
Follow the below steps to solve the problem:
- Initialize a min heap (priority queue) pq.
- For each element in the array:
- Push the element onto the max heap.
- If the size of the max heap exceeds K, pop (remove) the smallest element from the min heap. This step ensures that the min heap maintains the K largest elements encountered so far.
- After processing all elements, the min heap will contain the K largest elements of the array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void kLargest(vector< int >& v, int N, int K)
{
priority_queue< int , vector< int >, greater< int > > pq;
for ( int i = 0; i < N; ++i) {
pq.push(v[i]);
if (pq.size() > K) {
pq.pop();
}
}
while (!pq.empty()) {
cout << pq.top() << " " ;
pq.pop();
}
cout << endl;
}
int main()
{
vector< int > arr
= { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
int n = arr.size();
int k = 3;
cout << k << " largest elements are : " ;
kLargest(arr, n, k);
}
|
Java
import java.util.*;
class GFG {
static void kLargest( int a[], int n, int k)
{
PriorityQueue<Integer> pq
= new PriorityQueue<Integer>();
for ( int i = 0 ; i < n; ++i) {
pq.add(a[i]);
if (pq.size() > k) {
pq.poll();
}
}
while (!pq.isEmpty()) {
System.out.print(pq.peek() + " " );
pq.poll();
}
System.out.println();
}
public static void main(String[] args)
{
int a[]
= { 11 , 3 , 2 , 1 , 15 , 5 , 4 , 45 , 88 , 96 , 50 , 45 };
int n = a.length;
int k = 3 ;
System.out.print(k + " largest elements are : " );
kLargest(a, n, k);
}
};
|
Python3
import heapq
def kLargest(v, N, K):
pq = []
heapq.heapify(pq)
for i in range (N):
heapq.heappush(pq, v[i])
if ( len (pq) > K):
heapq.heappop(pq)
while ( len (pq) ! = 0 ):
print (heapq.heappop(pq), end = ' ' )
print ()
arr = [ 11 , 3 , 2 , 1 , 15 , 5 , 4 , 45 , 88 , 96 , 50 , 45 ]
n = len (arr)
k = 3
print (k, " largest elements are : " , end = '')
kLargest(arr, n, k)
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
static void kLargest( int [] a, int n, int k)
{
SortedSet< int > pq = new SortedSet< int >();
for ( int i = 0; i < n; ++i)
{
pq.Add(a[i]);
if (pq.Count > k) {
pq.Remove(pq.Min);
}
}
while (pq.Count > 0) {
Console.Write(pq.Max + " " );
pq.Remove(pq.Max);
}
Console.WriteLine();
}
public static void Main( string [] args)
{
int [] a
= { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
int n = a.Length;
int k = 3;
Console.Write(k + " largest elements are : " );
kLargest(a, n, k);
}
}
|
Javascript
function kLargest(v, N, K) {
const pq = [];
v.forEach(val => pq.push(val));
pq.sort((a, b) => a - b);
if (pq.length > K) {
pq.splice(0, pq.length - K);
}
while (pq.length !== 0) {
console.log(pq.shift());
}
console.log();
}
const arr = [11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45];
const n = arr.length;
const k = 3;
console.log(`${k} largest elements are: `);
kLargest(arr, n, k);
|
Output3 largest elements are : 50 88 96
Time Complexity: O(N * log(K))
Auxiliary Space: O(K)