sagelearnai

Kth Largest Element in an Array

Difficulty: Medium · Pattern: Heap & Priority Queue · LeetCode #215

Return the k-th largest element of nums, counting duplicates (the k-th element of the array sorted in descending order). Can you beat sorting?

Examples

text
nums = [7, 2, 9, 4, 1], k = 2           →  7
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4  →  4

Hints

  1. Sorting is O(n log n).
  2. Keep the k largest values seen so far in a min-heap: its root is the k-th largest.
  3. Quickselect (partition like quicksort, recurse into one side) is O(n) on average.

Approach

Push each number into a min-heap; whenever its size exceeds k, pop the smallest. After processing everything, the heap contains the k largest values, and the root is the smallest of them, i.e., the k-th largest. O(n log k) time and O(k) space.

Quickselect gives O(n) average (O(n²) worst case, mitigated by a random pivot), and is worth mentioning as the follow-up.

Complexity

Time: O(n log k). Space: O(k). (Quickselect: O(n) average, O(1) extra.)

Python solution
import heapq

def findKthLargest(nums, k):
    h = []
    for x in nums:
        heapq.heappush(h, x)
        if len(h) > k:
            heapq.heappop(h)
    return h[0]
JavaScript solution
class MinHeap {
  constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
  get size() { return this.a.length; }
  peek() { return this.a[0]; }
  push(x) { const a = this.a; a.push(x); let i = a.length - 1;
    while (i > 0) { const p = (i - 1) >> 1; if (this.cmp(a[i], a[p]) >= 0) break; [a[i], a[p]] = [a[p], a[i]]; i = p; } }
  pop() { const a = this.a, top = a[0], last = a.pop();
    if (a.length) { a[0] = last; let i = 0;
      for (;;) { const l = 2 * i + 1, r = l + 1; let m = i;
        if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
        if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
        if (m === i) break; [a[i], a[m]] = [a[m], a[i]]; i = m; } }
    return top; }
}

function findKthLargest(nums, k) {
  const h = new MinHeap();
  for (const x of nums) { h.push(x); if (h.size > k) h.pop(); }
  return h.peek();
}