KatInterview

Running Median Over a Command Log of Inserts and Queries

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

Last updated

Process a log of insert and query commands on a growing multiset of integers, reporting the median at each query using two heaps for efficient updates.

You are given a log of commands that act on a growing collection of integers, which starts out empty. The commands are supplied as two parallel lists of equal length:

  • commands[i] is the name of the i-th command.
  • payloads[i] is a list of arguments for that command.

Two command names exist:

  • "addNum": payloads[i] holds exactly one integer. Insert it into the collection (duplicates are allowed and each copy counts separately). This command produces no result.
  • "findMedian": payloads[i] is an empty list. Report the median of every integer inserted so far.

Median definition. Sort all inserted integers. If their count is odd, the median is the middle value. If the count is even, the median is the average of the two middle values.

Output. Return a list with one entry per command, in the same order as the input:

  • None for each "addNum" command.
  • The median as a floating-point number for each "findMedian" command (for example 2.0 rather than 2, and 1.5 for the average of 1 and 2).

Any unrecognized command name is not expected to appear in the input.

Aim for an approach where each insertion costs about O(log n) and each median query costs O(1), rather than re-sorting the collection for every query.

Constraints

  • The total number of commands is at most 100,000.
  • Each inserted integer lies in the range -10^6 to 10^6.
  • "findMedian" is only issued after at least one integer has been inserted.
  • commands and payloads have the same length.
  • Edge cases to handle: a single inserted element, all-identical elements, and negative values and zero.

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', 'findMedian', 'addNum', 'findMedian'], [[-1], [], [-2], []])

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

Hints

Hint 1

Splitting the numbers into a smaller half and a larger half means the median always sits at the boundary between them, so you never need the full sorted order.

Hint 2

Use a max-heap for the smaller half and a min-heap for the larger half. Python's heapq is a min-heap, so store negated values for the max-heap.

Hint 3

After every insertion, keep the two halves ordered (everything in the smaller half is at most everything in the larger half) and keep their sizes equal, or with the smaller half holding exactly one extra element. One element transfer is always enough to rebalance.