Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Created April 17, 2023 13:29
Show Gist options
  • Select an option

  • Save optimistiks/fa95c4e98d75b0fc6f7d88bd2721539a to your computer and use it in GitHub Desktop.

Select an option

Save optimistiks/fa95c4e98d75b0fc6f7d88bd2721539a to your computer and use it in GitHub Desktop.
Find the kth largest element in an unsorted array.
export function findKthLargest(arr, k) {
// we are going to have min heap of size k
// it means the top of the heap is going to be the minimum element
// of all k elements in the heap
// which is exactly the kth largest element that we need
const heap = new MinHeap();
for (let i = 0; i < k; ++i) {
// initialize the heap with the first k elements from the array
heap.offer(arr[i]);
}
for (let i = k; i < arr.length; ++i) {
// iterate the rest of the array
if (arr[i] > heap.peek()) {
// if array element is larger than the top of the heap,
// it means top of the heap is not part of the k largest elements,
// so we remove it, and push the current element to the heap
heap.poll();
heap.offer(arr[i]);
}
}
// top of the min heap is the kth largest element
return heap.peek();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment