KatInterview

Streaming Median Query

Data Structure DesignAuto-graded · 17 test cases
HardAuto-gradedData Structure Designheapsdata-structuresstreaming

Last updated

Tests balanced heap design to maintain dynamic order statistics with logarithmic insertions and constant-time median queries.

Streaming Median Query

Build a system that processes a sequence of operations on a numeric stream. The system must support two operations:

  1. Adding a number to the stream
  2. Querying the current median of all numbers seen so far

You will receive two parallel lists:

  • operations: a list of operation names, each either "add_num" or "find_median"
  • arguments: a list of argument lists, where arguments[i] contains the arguments for operations[i]

For "add_num" operations, the argument list contains a single integer to add to the stream.
For "find_median" operations, the argument list is empty.

Return a list of results where:

  • "add_num" operations produce None in the output
  • "find_median" operations produce the median as a float

Median definition:

  • If the count of numbers is odd, return the middle value
  • If the count is even, return the arithmetic mean of the two middle values
  • If no numbers have been added yet, return 0.0

Constraints

  • 1 <= len(operations) <= 50000
  • operations[i] is either "add_num" or "find_median"
  • -1000000 <= num <= 1000000 for any number added
  • len(operations) == len(arguments)
  • Your solution must handle insertions in O(log n) time and median queries in O(1) time, where n is the current count of numbers

Examples

Example 1

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

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

Example 2

Input: streaming_median(['find_median', 'add_num', 'find_median', 'add_num', 'find_median'], [[], [-5], [], [5], []])

Output: [0, None, -5, None, 0]

Hints

Hint 1

The median only depends on the middle element(s) of sorted order—you don't need to maintain a fully sorted list

Hint 2

Two heaps can partition the stream: one holding the smaller half and one holding the larger half

Hint 3

Python's heapq is a min-heap, but you can simulate a max-heap by negating values