KatInterview

Median Tracker for an Incoming Number Feed

Heaps, Sorting & SearchAuto-graded · 24 test cases
MediumAuto-gradedHeaps, Sorting & Searchheaptwo-heapsstreaming

Last updated

Maintain the median of a growing sequence after each new value arrives, testing efficient order-statistic upkeep with a pair of heaps.

Median Tracker for an Incoming Number Feed

A sensor sends integer readings one at a time. The readings are given in arrival order in the list readings. Right after each reading arrives, you must record the median of every reading received up to and including that one.

Return a list with one median per arrival, in arrival order.

Definition of the median

Sort all readings received so far.

  • If the count is odd, the median is the middle value of the sorted list.
  • If the count is even, the median is the average of the two middle values of the sorted list.

Rules

  • The result at index i is the median of readings[0..i] (inclusive).
  • Repeated values are distinct readings, and each one is counted.
  • Every result must be a Python float, including medians that are whole numbers (for example 5.0, not 5).
  • Each median is either a whole number or a whole number plus one half, so it can be represented exactly.

Constraints

  • 1 <= len(readings) <= 5 * 10^4
  • -10^5 <= readings[i] <= 10^5

Examples

Example 1

Input: running_median_feed([5, 2, 8, 1])

Output: [5, 3.5, 5, 3.5]

Example 2

Input: running_median_feed([-3, -3, 4])

Output: [-3, -3, -3]

Example 3

Input: running_median_feed([1, 10, 2, 9])

Output: [1, 5.5, 2, 5.5]

Hints

Hint 1

Re-sorting the whole prefix after every arrival is too slow for 50,000 values. Think about what you actually need: only the middle one or two elements.

Hint 2

Split the received values into a lower half and an upper half so that everything in the lower half is at most everything in the upper half. Which data structure gives quick access to the largest of one half and the smallest of the other?

Hint 3

Use a max-heap (negated values in Python's heapq) for the lower half and a min-heap for the upper half. After each insert, rebalance so the lower half has the same size as the upper half or exactly one more element, then read the median from the heap tops.