KatInterview

Running Median from Integer Stream

Heaps, Sorting & SearchAuto-graded · 16 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapsstreaming-algorithmsdata-structures

Last updated

Tests ability to maintain order statistics efficiently in a streaming context using heap-based data structures.

Build a system that processes integers one at a time and computes the median of all values seen so far after each operation.

You will receive a sequence of operations:

  • "add" with argument [x]: insert integer x into the collection
  • "getMedian" with argument []: return the current median as a float

The median is defined as:

  • For an odd number of elements: the middle value when sorted
  • For an even number of elements: the average of the two middle values when sorted

Your function receives two parallel lists: operations (strings) and arguments (lists of integers). Process each operation in order and return a list of results:

  • For "add": append None to the result
  • For "getMedian": append the median as a float
  • If "getMedian" is called before any values are added, raise a ValueError
  • If an unknown operation is encountered, raise a ValueError

Constraints

  • 1 ≤ number of operations ≤ 10⁵
  • -10⁹ ≤ x ≤ 10⁹
  • At least one operation will be present
  • "getMedian" operations will not exceed the number of preceding "add" operations in valid test cases

Examples

Example 1

Input: running_median(['add', 'add', 'add', 'getMedian', 'add', 'getMedian'], [[2], [3], [1], [], [4], []])

Output: [None, None, None, 2, None, 2.5]

Example 2

Input: running_median(['add', 'getMedian', 'add', 'getMedian'], [[5], [], [5], []])

Output: [None, 5, None, 5]

Hints

Hint 1

The median only depends on the one or two middle elements, not the entire sorted order

Hint 2

Consider maintaining two collections: one for values below the median and one for values above it

Hint 3

Use heap data structures to efficiently track the largest value in the lower half and the smallest value in the upper half