KatInterview

Replay Commands to Track a Running Median

Heaps, Sorting & SearchAuto-graded · 14 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapstreamingmedian

Last updated

Replay a list of insert and query commands on a growing multiset of integers, reporting the median at each query; tests two-heap or order-statistic maintenance.

You are given a log of commands that act on a growing collection of integers. The collection starts empty. Process the commands in order and report what each one produces.

Two kinds of commands exist:

  • "addNum": its argument list holds exactly one integer x. Put x into the collection. Duplicates are kept as separate items. This command produces None.
  • "findMedian": its argument list is empty. Compute the median of everything added so far and produce it as a float.

Median. Sort the collection mentally.

  • With an odd number of items, the median is the middle item.
  • With an even number of items, the median is the average of the two middle items.

Input.

  • operations: a list of command names, each either "addNum" or "findMedian".
  • arguments: a list of the same length as operations. Entry i is the argument list for command i ([x] for addNum, [] for findMedian).

Output. A list with one entry per command, in order: None for each addNum, and the median as a float for each findMedian.

Rules.

  • A findMedian command is only issued when the collection has at least one item.
  • If a command name is anything other than "addNum" or "findMedian", raise ValueError.

A solution that handles each insertion in roughly O(log n) time and each query in O(1) or O(log n) time is expected.

Constraints

  • The number of commands is up to about 10^5.
  • Added values are integers; they may be negative and may repeat.
  • Every findMedian follows at least one addNum.

Examples

Example 1

Input: running_median_log(['addNum', 'addNum', 'findMedian', 'addNum', 'findMedian'], [[1], [2], [], [3], []])

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

Example 2

Input: running_median_log(['addNum', 'addNum', 'addNum', 'findMedian', 'addNum', 'findMedian'], [[-1], [-2], [-3], [], [4], []])

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

Hints

Hint 1

Re-sorting the whole collection on every query is too slow. Think about which elements you actually need to see: only the one or two in the middle.

Hint 2

Keep the smaller half of the numbers in a max-heap and the larger half in a min-heap, so the middle elements sit at the two heap tops.

Hint 3

After each insertion, route the value to the correct half, then move at most one element between heaps so the lower half has the same size as the upper half or one more. Python's heapq is a min-heap, so store negated values for the lower half.