মূল কনটেন্টে যান
🛰️
রিমোট DSA
প্যাটার্নটপিক 6 · Heaps / Priority Queues

6.1 Top K Elements

চিনবেন কীভাবে
"k largest/smallest", "kth largest", "k most frequent", "k closest" — keep a heap of size k instead of sorting everything: O(n log k)
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: Kth Largest Element in an ArrayLC 215 (Medium — Amazon/Meta/Google High)

Statement (Demo): Given an integer array nums and an integer k, return the k-th largest element in sorted order (not the k-th distinct). Example: nums=[3,2,1,5,6,4], k=25 | ⚡ 1 ≤ k ≤ n ≤ 10⁵, -10⁴ ≤ nums[i] ≤ 10⁴

Approach: JavaScript has no built-in heap, so write a small MinHeap once — every heap pattern (6.x, Dijkstra in 8.6) reuses it. Keep a min-heap of the k largest seen so far: push each number, and when the size passes k, pop the smallest. The top is then the k-th largest.

class MinHeap {
  constructor(compare = (a, b) => a - b) {
    this.data = [];
    this.compare = compare;
  }
  get size() {
    return this.data.length;
  }
  peek() {
    return this.data[0];
  }
  push(value) {
    const d = this.data;
    d.push(value);
    let i = d.length - 1;
    while (i > 0) {
      const parent = (i - 1) >> 1;
      if (this.compare(d[i], d[parent]) >= 0) break;
      [d[i], d[parent]] = [d[parent], d[i]]; // sift up
      i = parent;
    }
  }
  pop() {
    const d = this.data;
    const top = d[0];
    const last = d.pop();
    if (d.length) {
      d[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1,
          r = l + 1;
        let smallest = i;
        if (l < d.length && this.compare(d[l], d[smallest]) < 0) smallest = l;
        if (r < d.length && this.compare(d[r], d[smallest]) < 0) smallest = r;
        if (smallest === i) break;
        [d[i], d[smallest]] = [d[smallest], d[i]]; // sift down
        i = smallest;
      }
    }
    return top;
  }
}

function findKthLargest(nums, k) {
  const heap = new MinHeap();
  for (const x of nums) {
    heap.push(x);
    if (heap.size > k) heap.pop(); // drop the smallest — keep the k largest
  }
  return heap.peek();
}

Complexity: Time O(n log k), Space O(k) (quickselect gives O(n) average — mention it as a follow-up)

Demo · Kth Largest Element in an Arrayplan · দিন ০৩৩LC 215
নোট · ফাঁকা

প্রবলেম

  • Top K Frequent Elementsplan · দিন ০৩৬LC 347
    (count with a map, then a size-k heap on counts — or bucket sort for O(n))

    Statement: Given an integer array nums and an integer k, return the k most frequent elements, in any order.
    Example: nums=[1,1,1,2,2,3], k=2[1,2] | ⚡ n ≤ 10⁵, answer is unique

    নোট · ফাঁকা
  • K Closest Points to Originplan · দিন ০৩৭LC 973
    (max-heap of size k on squared distance)

    Statement: Given points on a plane and an integer k, return the k points closest to the origin (0, 0) by Euclidean distance, in any order.
    Example: points=[[1,3],[-2,2]], k=1[[-2,2]] | ⚡ 1 ≤ k ≤ n ≤ 10⁴

    নোট · ফাঁকা
  • Kth Largest Element in a StreamLC 703
    (the demo, but the numbers keep arriving)

    Statement: Design KthLargest(k, nums) whose add(val) inserts a number and returns the current k-th largest of everything added so far.
    Example: k=3, nums=[4,5,8,2]; add(3)=4, add(5)=5, add(10)=5 | ⚡ at most 10⁴ calls

    নোট · ফাঁকা
  • (max-heap simulation — the easiest heap problem)

    Statement: Each turn, smash the two heaviest stones x ≤ y: if equal both vanish, otherwise one stone of weight y - x remains. Return the last stone's weight, or 0.
    Example: stones=[2,7,4,1,8,1]1 | ⚡ n ≤ 30, 1 ≤ stones[i] ≤ 1000

    নোট · ফাঁকা
আরও দেখুন
Sliding Window Maximum with a heap → compare with the deque in 4.4