KatInterview

Running Median After Each Insertion

Heaps, Sorting & SearchAuto-graded · 17 test cases
EasyAuto-gradedHeaps, Sorting & Searchheapssortingmedian maintenance

Last updated

Tests median maintenance using two heaps to efficiently return the running median after each element is added to a growing sequence.

Running Median After Each Insertion

You are given a list of integers representing values that arrive one at a time in order. After each new value is inserted, you must report the median of all values seen so far.

The median is defined as:

  • If the current count of values is odd, the median is the middle value when all seen values are sorted.
  • If the current count of values is even, the median is the average of the two middle values (as a float).

Given a list stream of n integers, return a list of n numbers where the i-th element is the median after the first i+1 values have been inserted.

Each element in the result should be either an int (when the count so far is odd) or a float (when the count so far is even). Specifically:

  • Odd count → return the exact integer median (type int).
  • Even count → return (left + right) / 2 as a float.

Constraints

  • 1 ≤ len(stream) ≤ 2000
  • -10^6 ≤ stream[i] ≤ 10^6
  • The output list has exactly len(stream) elements.
  • When n is odd, the median element is an int; when n is even, it is a float.

Examples

Example 1

Input: running_median([5])

Output: [5]

Example 2

Input: running_median([3, 1, 4, 1, 5])

Output: [3, 2, 3, 2, 3]

Example 3

Input: running_median([10, -10, 0])

Output: [10, 0, 0]

Hints

Hint 1

Think of maintaining two heaps: a max-heap for the lower half and a min-heap for the upper half of the seen values.

Hint 2

After each insertion, rebalance the two heaps so their sizes differ by at most 1. The median is then either the top of the larger heap (odd count) or the average of both tops (even count).

Hint 3

Python's heapq only provides a min-heap; negate values to simulate a max-heap for the lower half.