KatInterview

Stream Median Tracker

Heaps, Sorting & SearchAuto-graded · 14 test cases
EasyAuto-gradedHeaps, Sorting & Searchheapsheapqdata-structures

Last updated

Process a series of dynamic data stream queries to compute the median on demand using heap-based structures.

You are asked to process a sequence of operations on a dynamic integer stream structure.

The operations are given as two parallel lists, operations and arguments:

  1. "MedianFinder": Initializes (or resets) the internal state. The corresponding argument is []. The return value for this command should be None.
  2. "add_num": Receives a single integer passed in arguments[i] (e.g., [x]) and inserts it into the data stream. The return value for this command should be None.
  3. "find_median": Calculates the current median of all integers inserted so far. The corresponding argument is []. The return value should be a float. If the count of inserted numbers is odd, the median is the middle value. If the count is even, the median is the arithmetic mean of the two central values.

Your function should return a list containing the output of each operation in order.

Constraints

  • Total calls to add_num and find_median will not exceed $5 \times 10^4$.
  • Each stream value lies within the range $[-10^5, 10^5]$.
  • find_median will only be called after at least one number has been added to the stream.

Edge Cases

  • Stream contains negative numbers.
  • Consecutive identical numbers are added.
  • Alternate queries on odd and even numbers of elements.

Examples

Example 1

Input: median_finder(['MedianFinder', 'add_num', 'add_num', 'find_median', 'add_num', 'find_median'], [[], [1], [2], [], [3], []])

Output: [None, None, None, 1.5, None, 2]

Example 2

Input: median_finder(['MedianFinder', 'add_num', 'add_num', 'add_num', 'find_median'], [[], [5], [5], [5], []])

Output: [None, None, None, None, 5]

Hints

Hint 1

To get O(log N) insertion and O(1) median retrieval, split the data into two halves using two heaps.

Hint 2

Use a max-heap for the smaller half of the numbers and a min-heap for the larger half.

Hint 3

Keep the sizes of both heaps balanced so that the max-heap has either equal size or exactly one more element than the min-heap.