0
0
DSA Typescriptprogramming~3 mins

Why Median of Data Stream Using Two Heaps in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

What if you could instantly know the middle value of a never-ending list without sorting it every time?

The Scenario

Imagine you are tracking the middle value of a growing list of numbers, like daily temperatures or scores, but you get the numbers one by one and want to know the middle value at any time.

Doing this by sorting the whole list every time a new number arrives is like rearranging your entire bookshelf every time you get a new book--slow and tiring!

The Problem

Sorting the entire list after each new number is slow because it takes more time as the list grows.

Also, manually finding the middle value each time is error-prone and wastes a lot of effort.

The Solution

Using two heaps (special boxes that keep numbers in order) lets you quickly find the middle value without sorting everything again.

One heap keeps the smaller half of numbers, the other keeps the bigger half, so the middle is always easy to find.

Before vs After
Before
numbers.push(newNumber);
numbers.sort((a, b) => a - b);
const mid = Math.floor(numbers.length / 2);
const median = numbers.length % 2 === 0 ? (numbers[mid - 1] + numbers[mid]) / 2 : numbers[mid];
After
const maxHeap = new MaxHeap();
const minHeap = new MinHeap();
addNumber(newNumber);
const median = getMedian();
What It Enables

This method lets you find the middle value instantly as new numbers come in, even if the list grows very large.

Real Life Example

Streaming apps use this to show the median rating of a movie as viewers keep rating it live, without waiting for all ratings to finish.

Key Takeaways

Manually sorting each time is slow and inefficient.

Two heaps keep track of smaller and larger halves separately.

Median can be found quickly without full sorting.