BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / MLOps25 of 26 in topic

792. Track the running median of a latency stream

MediumMLOps Pro

Dashboards often show the median latency of a model endpoint as requests arrive. Sorting the whole history after every request is too slow, so you need a structure that updates in log time.

Write running_medians(stream). stream is a list of numbers that arrive one at a time. Return a list with the median after each arrival. With an odd count the median is the middle value; with an even count it is the mean of the two middle values. Return every median as a float.

An empty stream returns an empty list.

Functiondef running_medians(stream)

Example 1

Input: running_medians([5, 15, 1, 3])

Output: [5.0, 10.0, 5.0, 4.0]

Example 2

Input: running_medians([2, 2, 2])

Output: [2.0, 2.0, 2.0]

Constraints

  • 0 <= len(stream) <= 200,000
  • Values are ints or floats
Hint 1

Use heapq with negated values for the max heap.

Hint 2

Rebalance after every push.

Hint 3

Decide the median from the heap sizes.

Common mistakes
  • Forgetting to negate when popping from the max heap.
  • Letting the heaps differ in size by two or more.
  • Returning ints for odd counts when floats are required.
Understand the idea

The two heap trick keeps a sorted split without sorting. For [5, 15, 1, 3]: after 5, low = {5}; after 15, high = {15}, median 10; after 1, low = {5, 1}, median 5; after 3, low = {5, 3, 1} is too big, so 5 moves to high = {5, 15}, and the median is (3 + 5) / 2 = 4. The same idea backs streaming p50 monitors. For other percentiles, production systems usually switch to approximate sketches, because exact heaps keep every value in memory.

Topics
MLOps
Similar questions
  • Catch train-serving skew in feature pipelinesMedium
  • Drive a staged canary rollout from per-window error ratesMedium
  • Pick a champion model with guardrail metricsMedium
  • Measure feature drift with smoothed KL divergence on quantile binsMedium
All MLOps problems
Report
792 / 903
Python 3solution.pyPython idle
1
2
3
4
def running_medians(stream):
# return a list of floats, one median per arrival
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS