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

6.3 Two Heaps

চিনবেন কীভাবে
"median of a stream", "balance two halves", "sliding window median" — a max-heap for the smaller half, a min-heap for the larger half, sizes kept within one
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: Find Median from Data StreamLC 295 (Hard — Amazon/Google/Meta High)

Statement (Demo): Design MedianFinder with addNum(num) and findMedian(), which returns the median of every number added so far (the mean of the two middles for an even count). Example: addNum(1), addNum(2), findMedian()=1.5, addNum(3), findMedian()=2.0 | ⚡ at most 5×10⁴ calls

Approach: low is a max-heap of the smaller half, high a min-heap of the larger half. Push every number into low, move low's top to high (so every low ≤ every high), then move back if high got bigger. The median is low's top, or the mean of both tops. (MinHeap → 6.1; a max-heap is the same class with a reversed compare.)

class MedianFinder {
  constructor() {
    this.low = new MinHeap((a, b) => b - a); // max-heap: smaller half
    this.high = new MinHeap(); // min-heap: larger half
  }
  addNum(num) {
    this.low.push(num);
    this.high.push(this.low.pop()); // keep every low ≤ every high
    if (this.high.size > this.low.size) this.low.push(this.high.pop()); // low may hold one extra
  }
  findMedian() {
    return this.low.size > this.high.size
      ? this.low.peek()
      : (this.low.peek() + this.high.peek()) / 2;
  }
}

Complexity: addNum O(log n), findMedian O(1), Space O(n)

Demo · Find Median from Data Streamplan · দিন ০৬৬LC 295
নোট · ফাঁকা

প্রবলেম

  • Sliding Window MedianLC 480
    (Hard — two heaps + lazy deletion of numbers that left the window)

    Statement: Given an integer array nums and an integer k, return the median of every window of size k as it slides from left to right.
    Example: nums=[1,3,-1,-3,5,3,6,7], k=3[1,-1,-1,3,5,6] | ⚡ k ≤ n ≤ 10⁵

    নোট · ফাঁকা