Efficiently Computing the Running Median in TypeScript Using Heaps
A Step-by-Step Guide to Calculating the Running Median of a Number Stream with Optimized Algorithms
If you’re not a medium member, you can read the story through this link.
Problem
Compute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element.
Recall that the median of an even-numbered list is the average of the two middle numbers.
For example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out:
2
1.5
2
3.5
2
2
2
Problem Breakdown
Median Definition:
For an odd-sized list, the median is the middle element.
For an even-sized list, the median is the average of the two middle elements.
Efficient Calculation:
We need to efficiently insert numbers into the list and then quickly find the median after each insertion.
Maintaining a sorted list would work, but re-sorting the list after each insertion is costly (O(n log n)).