Skip to content
DSA Patterns
Menu
Language
Heap & Top KLC #2152 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Kth Largest Element in an Array

Problem (restated)

Find the kth largest element in an unsorted array (not distinct required).

Intuition

Min-heap of size k holds the largest k seen; root is kth largest. Quick select partitions until index n-k is the pivot.

Approaches

Min-heap of size k

Unverified
Time O(n log k)Space O(k)

Idea. Push all; pop when size>k; return peek.

Walkthrough. [3,2,1,5,6,4], k=2 → 5.

Trade-offs. Heap O(n log k) vs quickselect average O(n). Prefer the heap when k is tiny or the array must stay intact.

Solution
Show helper code
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
  private a: T[] = [];
  private less: (x: T, y: T) => boolean;
  constructor(less: (x: T, y: T) => boolean) {
    this.less = less;
  }
  get size(): number {
    return this.a.length;
  }
  peek(): T {
    return this.a[0]!;
  }
  push(x: T): void {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.less(a[i]!, a[p]!)) break;
      [a[i], a[p]] = [a[p]!, a[i]!];
      i = p;
    }
  }
  pop(): T {
    const a = this.a;
    const top = a[0]!;
    const last = a.pop()!;
    if (a.length) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let s = i;
        if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
        if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
        if (s === i) break;
        [a[i], a[s]] = [a[s]!, a[i]!];
        i = s;
      }
    }
    return top;
  }
}
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
  private a: T[] = [];
  private less: (x: T, y: T) => boolean;
  constructor(less: (x: T, y: T) => boolean) {
    this.less = less;
  }
  get size(): number {
    return this.a.length;
  }
  peek(): T {
    return this.a[0]!;
  }
  push(x: T): void {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.less(a[i]!, a[p]!)) break;
      [a[i], a[p]] = [a[p]!, a[i]!];
      i = p;
    }
  }
  pop(): T {
    const a = this.a;
    const top = a[0]!;
    const last = a.pop()!;
    if (a.length) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let s = i;
        if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
        if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
        if (s === i) break;
        [a[i], a[s]] = [a[s]!, a[i]!];
        i = s;
      }
    }
    return top;
  }
}
export function findKthLargest(nums: number[], k: number): number {
  // Real binary min-heap of size k; its top is the kth largest.
  const heap = new Heap<number>((a, b) => a < b);
  for (const x of nums) {
    if (heap.size < k) {
      heap.push(x);
    } else if (x > heap.peek()) {
      heap.pop();
      heap.push(x);
    }
  }
  return heap.peek();
}
export function findKthLargest(nums: number[], k: number): number {
  // Real binary min-heap of size k; its top is the kth largest.
  const heap = new Heap<number>((a, b) => a < b);
  for (const x of nums) {
    if (heap.size < k) {
      heap.push(x);
    } else if (x > heap.peek()) {
      heap.pop();
      heap.push(x);
    }
  }
  return heap.peek();
}

Quick select

Unverified
Time O(n) averageSpace O(1)

Idea. The kth largest is the element at index n-k in sorted order. Randomized partition until the pivot lands there; loop into only one side. Mutates the array in place.

Walkthrough. [3,2,1,5,6,4], k=2 → target index 4. After partitions the value at index 4 is 5.

Trade-offs. Average O(n), worst O(n²) without a random pivot. The Quick Select default. k is 1-indexed.

Solution
export function findKthLargest(nums: number[], k: number): number {
  const target = nums.length - k;
  let lo = 0, hi = nums.length - 1;
  while (lo <= hi) {
    const p = partition(nums, lo, hi);
    if (p === target) return nums[p]!;
    if (p < target) lo = p + 1;
    else hi = p - 1;
  }
  return nums[lo]!;
}

function partition(nums: number[], lo: number, hi: number): number {
  const rand = lo + Math.floor(Math.random() * (hi - lo + 1));
  [nums[rand], nums[hi]] = [nums[hi]!, nums[rand]!];
  const pivot = nums[hi]!;
  let i = lo;
  for (let j = lo; j < hi; j++) {
    if (nums[j]! < pivot) {
      [nums[i], nums[j]] = [nums[j]!, nums[i]!];
      i++;
    }
  }
  [nums[i], nums[hi]] = [nums[hi]!, nums[i]!];
  return i;
}
export function findKthLargest(nums: number[], k: number): number {
  const target = nums.length - k;
  let lo = 0, hi = nums.length - 1;
  while (lo <= hi) {
    const p = partition(nums, lo, hi);
    if (p === target) return nums[p]!;
    if (p < target) lo = p + 1;
    else hi = p - 1;
  }
  return nums[lo]!;
}

function partition(nums: number[], lo: number, hi: number): number {
  const rand = lo + Math.floor(Math.random() * (hi - lo + 1));
  [nums[rand], nums[hi]] = [nums[hi]!, nums[rand]!];
  const pivot = nums[hi]!;
  let i = lo;
  for (let j = lo; j < hi; j++) {
    if (nums[j]! < pivot) {
      [nums[i], nums[j]] = [nums[j]!, nums[i]!];
      i++;
    }
  }
  [nums[i], nums[hi]] = [nums[hi]!, nums[i]!];
  return i;
}

Template connection

Heap top-K, or Quick Select to rank n-k. Classic kth-largest problem for both patterns.

Reflection

  • The top of a min-heap of size k is the kth largest. Push every value and pop once the size passes k. Quickselect is linear on average.
  • k == n is the smallest value. k == 1 is the largest. Duplicates are distinct elements. Do not unique them.
  • A bad pivot makes quickselect quadratic. The heap stays O(n log k).
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Kth largest in [3,2,1,5,6,4], k=2. Keep a min-heap of size k.

3
0
2
1
1
2
5
3
6
4
4
5

k = 2 · min-heap

Key:CurrentActive rangeLeft / slowMatchSettledEliminated