Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Kth largest element in the unsorted array

Moderate
0/80
Average time to solve is 10m
profile
Contributed by
27 upvotes
Asked in companies
FacebookUberMicrosoft

Problem statement

You are given an array consisting of 'N' distinct positive integers and a number 'K'. Your task is to find the kth largest element in the array.

Example:
Consider the array {2,1,5,6,3,8} and 'K' = 3, the sorted array will be {8, 6, 5, 3, 2, 1}, and the 3rd largest element will be 5.
Note:
1) Kth largest element in an array is the kth element of the array when sorted in non-increasing order. 

2) All the elements of the array are pairwise distinct.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of the input contains an integer 'T' denoting the number of test cases.

The first line of each test case contains two space- separated integers 'N' and 'K', as described in the problem statement.

The second line of each test case contains 'N' space-separated integers, representing the elements of the array.
Output Format:
For each test case, print a single integer denoting the kth largest number in the given array.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N <= 10^4
1 <= ARR[i] <= 10^9
1 <= K <= N

Time Limit: 1 sec
Sample Input 1:
1
3 1
1 2 3
Sample Output 1:
3
Explanation for sample input 1:
3 is the first largest element in the array {1,2,3}.
Sample Input 2:
1
4 2
5 6 7 8
Sample Output 2:
7
Explanation for sample input 2:
7 is the second largest element in the array {5,6,7,8}.
Hint

Sort the array.

Approaches (2)
Brute Force
  • The most obvious brute force approach would be to sort the array in descending order and return the ‘K’th element from the beginning of the array.
  • Sort the array in descending order, for sorting most of the languages have their inbuilt sort methods which are usually very fast.
  • After sorting, return the element arr['K'-1](i.e. element at index ‘K’-1, considering 0-based indexing).
Time Complexity

O( N * log(N) ), where ‘N’ is the size of the array.

 

We can sort an array in O(N * log(N)).

Space Complexity

O(1).

 

No extra space is used. 

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Kth largest element in the unsorted array
All tags
Sort by
Search icon

Interview problems

Easy Java Solution

import java.util.* ;

import java.io.*; 

public class Solution {

 

    static int kthLargest(ArrayList<Integer> arr, int size, int K) {

        // Write your code here.

        PriorityQueue<Integer>q=new PriorityQueue<>();

        for(int num:arr){

            q.add(num);

            if(q.size()>K) q.poll();

        }

        return q.peek();

    }

}

 

2 views
0 replies
0 upvotes

Interview problems

JAVA SOLUTION || Kth largest element in the unsorted array ||

import java.util.* ;

import java.io.*; 

public class Solution {

    static int kthLargest(ArrayList<Integer> arr, int size, int K) {

        PriorityQueue<Integer> pq = new PriorityQueue<>();

        for(int i : arr)pq.add(i);

        while(pq.size() > K)pq.remove();

        return pq.peek();

    }

}

7 views
0 replies
0 upvotes

Interview problems

c++ solution

#include <bits/stdc++.h> 

int kthLargest(vector<int>& arr, int size, int K)

{

    sort(arr.begin(), arr.end());

    K = size-K;

    return arr[K];  

}

107 views
0 replies
0 upvotes

Interview problems

check this c++ soln

#include <bits/stdc++.h>

int kthLargest(vector<int>& arr, int size, int K)

{

// Write your code here.

priority_queue<int> pq;

 

for (int i = 0; i < size; i++) {

pq.push(arr[i]);

}

 

while (K != 1) {

pq.pop();

K--;

}

 

return pq.top();

}

44 views
0 replies
0 upvotes

Interview problems

Easy solution in c++

#include <bits/stdc++.h> 

int kthLargest(vector<int>& arr, int size, int K)

{

    // Write your code here.

    sort(arr.begin(),arr.end());

    return arr[size-K];

}

41 views
0 replies
0 upvotes

Interview problems

Esay solution using Queue / CPP All the test case pass

#include <bits/stdc++.h> 

int kthLargest(vector<int>& arr, int size, int K)

{

    priority_queue<int>num;

    for(int i=0; i<size; i++)

    {

        num.push(arr[i]);

    }

    while(K>1){

        num.pop();

        K--;

    }

    int p=num.top();

    return p;

}

56 views
0 replies
0 upvotes

Interview problems

Kth largest element in the unsorted array || Simple Solution

#include <bits/stdc++.h> 

int kthLargest(vector<int>& arr, int size, int K)

{

    // Write your code here.

    priority_queue<int> pq;

    for(int i=0;i<size;i++){

        pq.push(arr[i]);

    }

    while(K>1){

        pq.pop();

        K--;

    }

    int t=pq.top();

    return t;

}

56 views
0 replies
0 upvotes

Interview problems

java || min PriorityQueue

static int kthLargest(ArrayList<Integer> arr, int size, int K) {

        //implementing min PriorityQueue;

        PriorityQueue<Integer> pq=new PriorityQueue<>();

        for(int i=0;i<arr.size();i++){

            //inserting k element in min PriorityQueue;

            if(i<K){

                pq.add(arr.get(i));

            }

            //after that replacing all min with max element until we get all k max element;

            else{

                if(pq.peek()<arr.get(i)){

                    pq.poll();

                    pq.add(arr.get(i));

                }

            }

        }

        return pq.peek();

    }

55 views
0 replies
1 upvote

Interview problems

Kth largest element in the unsorted array:- Python Solution

  1. Time Complexity: O( N LOG N )
  2. Space Complexity: O( 1 )

 

    def kthLargest(arr, size, k):
    	arr.sort()
    	return arr[size-k]

python

Kth largest element in the unsorted array

16 views
0 replies
1 upvote

Interview problems

Java Solution

import java.util.* ;
import java.io.*; 
public class Solution {

	static int kthLargest(ArrayList<Integer> arr, int size, int K) {
		// Write your code here.
		PriorityQueue<Integer> pq = new PriorityQueue<>();
		for(int i : arr)pq.add(i);
		while(pq.size() > K)pq.remove();
		return pq.peek();
	}
}
111 views
0 replies
1 upvote
Full screen
Console