Efficiently Computing the Running Median in TypeScript Using Heaps

Burhanuddin Hamzabhai
Burhanuddin’s Code Compendium
4 min readOct 3, 2024

--

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)).

--

--

Burhanuddin’s Code Compendium
Burhanuddin’s Code Compendium

Published in Burhanuddin’s Code Compendium

Delve into Burhanuddin’s Code Compendium, a comprehensive collection of expertly crafted solutions, detailed explanations of coding challenges. Perfect for developers seeking to enhance their skills and deepen their understanding of programming complexities.

Burhanuddin Hamzabhai
Burhanuddin Hamzabhai

Written by Burhanuddin Hamzabhai

Experienced in Android, iOS, and Hybrid App development. Specialize in web development, PWAs, UI/UX design, and online teaching.

No responses yet