Skip to content
DSA Patterns
Menu
Language
Quick SelectLC #7035 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 a Stream

Problem (restated)

Design a structure seeded with an integer array and k. Each add(val) inserts val and returns the current kth largest among all values seen so far.

Intuition

The stream never shrinks, so you only need the largest k values. A min-heap of size k: the root is the kth largest. A new value beats the root iff it is larger; then replace. Quick select is the wrong tool here; it is offline.

Approaches

Min-heap of size k

Unverified
Time O(log k) addSpace O(k)

Idea. Constructor pushes every seed through add. add pushes, pops if size > k, returns peek. If fewer than k values have arrived, the heap still has them all (constraints guarantee k is valid by the time you query).

Walkthrough. k=3, seed [4,5,8,2]. Heap [4,5,8]. add 3 → still 4. add 5 → 5. add 10 → 5. add 9 → 8.

Trade-offs. Streaming top-K is a heap, not a partition. Same size-k min-heap as LC 215, reused across calls.

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 class KthLargest {
  private k: number;
  // Real binary min-heap of size k; its top is the kth largest.
  private heap: Heap<number>;

  constructor(k: number, nums: number[]) {
    this.k = k;
    this.heap = new Heap<number>((a, b) => a < b);
    for (const x of nums) this.add(x);
  }

  add(val: number): number {
    if (this.heap.size < this.k) {
      this.heap.push(val);
    } else if (val > this.heap.peek()) {
      this.heap.pop();
      this.heap.push(val);
    }
    return this.heap.peek();
  }
}
export class KthLargest {
  private k: number;
  // Real binary min-heap of size k; its top is the kth largest.
  private heap: Heap<number>;

  constructor(k: number, nums: number[]) {
    this.k = k;
    this.heap = new Heap<number>((a, b) => a < b);
    for (const x of nums) this.add(x);
  }

  add(val: number): number {
    if (this.heap.size < this.k) {
      this.heap.push(val);
    } else if (val > this.heap.peek()) {
      this.heap.pop();
      this.heap.push(val);
    }
    return this.heap.peek();
  }
}

Template connection

Streaming top K on the Quick Select page: the heap beats the root. Quick select would rebuild from scratch on every add.

Reflection

  • A min-heap of size k. Once it grows past k, drop the smallest. The top is the kth largest value seen so far.
  • Before k inserts the top is not yet the kth largest. The problem only queries after that many adds.
  • Equal values are distinct entries. k = 1 is the running maximum. Older small values fall off the top.
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

Stream kth largest. k=3, seed [4,5,8,2]. Keep a min-heap of size k: the root is the answer.

4
0
5
1
8
2
2
3

k = 3

Key:Active rangeMatchSettledEliminated