FrontendPro

148Implement a median tracker for a real-time data stream

hardAbout 60 minutesCodingheapsdata-structuresstreamingstatistics

Problem

A monitoring dashboard receives response times one by one and must show the median latency at any moment (the median resists outliers better than the average). Implement class MedianFinder (LeetCode 295):

  • addNum(num): add a number from the stream.
  • findMedian(): the median of all numbers so far: the middle value for an odd count, the average of the two middle values for an even count. Return null before any number was added.
  • size: how many numbers were added.

addNum must be O(log n) and findMedian O(1), so it keeps up with 100,000 events. JavaScript has no built-in heap: implement one.

const finder = new MedianFinder();
finder.addNum(1);
finder.addNum(2);
finder.findMedian(); // 1.5
finder.addNum(3);
finder.findMedian(); // 2

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Video walkthrough

Stuck? Watch someone solve it, then try again on your own.

Find Median from Data Stream - Heap & Priority Queue - Leetcode 295NeetCode on YouTubeOpen on YouTube

Step-by-step

Keep the smaller half of the numbers in a max-heap (low) and the larger half in a min-heap (high). The median is then at the top of one or both heaps.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 4 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever