KatInterview

Running Median Over a Live Integer Feed

Data Structure DesignAuto-graded · 16 test cases
HardAuto-gradedData Structure Designheapsdesignstreaming

Last updated

Tests whether a candidate can design a two-heap structure that inserts integers and queries the running median in better than O(N) time per operation.

Problem

You are building a component that processes a live feed of integers one at a time. At any point the system must be able to report the current median of every integer received so far.

Your implementation is driven by two parallel lists of equal length: a list of operation names and a list of argument lists. Supported operations:

  • "add_num" — records one integer. Returns None.
  • "find_median" — returns the current median as a float. Its argument list is always empty ([]).

Any unrecognized operation name should raise a ValueError.

Median Definition

Sort all integers recorded up to this point.

  • If the count is odd, the median is the single middle value.
  • If the count is even, the median is the arithmetic mean of the two middle values.

Always return a float (e.g. 2.0, not 2).

Input and Output

  • operations: a list of operation name strings.
  • arguments: a list of argument lists, one per operation.

Return a single list where each entry is the result of the corresponding operation (None for "add_num", a float for "find_median").

Constraints

  • Both "add_num" and "find_median" must run in better than O(N) time, where N is the total number of integers added so far.
  • All integers are in the range [-10^6, 10^6].
  • "find_median" is never called before at least one "add_num".
  • The feed may contain duplicate integers.
  • 1 <= len(operations) <= 10^4

Examples

Example 1

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

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

Hints

Hint 1

Think about splitting the numbers seen so far into two halves — a lower half and an upper half — so the median always sits right at the boundary between them. What data structures let you peek at the largest element of one group and the smallest element of the other in O(1)?

Hint 2

Python's heapq only provides a min-heap. You can simulate a max-heap for the lower half by pushing negated values: the minimum of the negated numbers is the maximum of the originals.

Hint 3

After every add_num, check two conditions: (1) the largest element in the lower half must be ≤ the smallest element in the upper half, and (2) the sizes must satisfy len(lower) == len(upper) or len(lower) == len(upper) + 1. At most one element swap between the heap tops restores both conditions.