Topics
Heap


Kth Largest Element in an Array (opens in a new tab)

  • Use PriorityQueue to save all the values in as a max heap
  • Dequeue k times to get the kth largest element
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var findKthLargest = function (nums, k) {
  const maxPQ = new MaxPriorityQueue();
 
  for (const num of nums) {
    maxPQ.enqueue(num, num);
  }
 
  while (k > 1) {
    maxPQ.dequeue();
    k--;
  }
 
  return maxPQ.front().element;
};
Complexity
  • Time: O(n * log(n))
  • Space: O(n)