What if you could instantly know the middle value of a never-ending list without sorting it every time?
Why Median of Data Stream Using Two Heaps in DSA Typescript?
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!
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.
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.
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];
const maxHeap = new MaxHeap(); const minHeap = new MinHeap(); addNumber(newNumber); const median = getMedian();
This method lets you find the middle value instantly as new numbers come in, even if the list grows very large.
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.
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.