Solved Problem - Kth Largest element

In this lesson, we'll discuss a solved heap problem.

Problem statement

Given an array, A[]A[], consisting of NN integers; for a given KK, find the KthK^{th} largest element in the array.

Input format

The first line consists of two integers NN and KK (1KN106)(1 \leq K \leq N \leq 10^6).

The second line consists of NN integers representing the array A[]A[] (1A[i]106)(1 \leq A[i] \leq 10^6).


Sample

Input 1

5 1
3 6 5 1 4

Output 1

6

Input 2

5 4
3 6 5 1 4

Output 2

3

Explanation

Sample 1: K=1K = 1 means the 1st1^{st} largest in the entire array which is 6.

Sample 2: K=4K = 4 means the 4th4^{th} element if you sort the array in non-increasing order. i.e 4th4^{th} element in [6 5 4 3 1], which is 3.


Brute force

The explanation for sample two suggests a very simple solution:

  • Sort the array
  • Print the KthK^{th} number from right

When sorting, taking O(NlogN)O(NlogN) time and printing the KthK^{th} element is a constant time operation.

Time complexity - O(NlogN)O(NlogN).

Get hands-on with 1400+ tech skills courses.