SarthakKeshari / CPP-Questions-and-Solutions

This repository aims to solve and create new problems from different spheres of coding. A path to help students to get access to solutions and discuss their doubts.
MIT License
45 stars 132 forks source link

k’th largest element in an array #306

Closed ayushjindal23 closed 3 years ago

ayushjindal23 commented 3 years ago

Issue Id you have worked upon -

167

Briefly explain your program logic -

We can easily solve this problem in 0(n.log(k)) by using a min-heap. The idea is to construct a min-heap of size k and insert the first k elements of array A[0.k-1] into the min-heap. Then for each of the remaining array elements A[k....n-1], if that element is more than the min-heap's root, replace the root with the current element. Repeat this process until the array is exhausted. Now we will be left with top k largest array elements in the min heap, and k'th largest element will reside at the root of the min-heap.

Screenshots(Attach 2 screenshots of your own input and output) -

INPUT: image

OUTPUT: image

Checklist:

Eg - If your code follow the below guidelines. Kindly change [] to [x]

All the conditions should be fulfilled for considering your code for merging -