KatInterview

Running Median of a Sliding Window

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

Last updated

Tests median maintenance by computing the running median after each element is inserted into a growing sequence, using a two-heap approach.

Running Median Stream

You are given a list of integers stream arriving one at a time. After each new integer is consumed, compute the median of all integers seen so far.

The median is defined as:

  • If the count of numbers seen so far is odd, the median is the middle element when sorted.
  • If the count of numbers seen so far is even, the median is the average of the two middle elements (as a float).

Return a list of medians (one per element), where each median is either an int (when the running count is odd) or a float (when the running count is even).

Note: Return the median as an int when it is a whole number resulting from an odd-length prefix, and as a float (e.g. 4.5) when it results from averaging two middle elements — even if that average is a whole number (e.g. return 4.0, not 4).

Constraints

  • 1 <= len(stream) <= 2000
  • -10^6 <= stream[i] <= 10^6
  • After an odd number of elements, return the median as an int.
  • After an even number of elements, return the median as a float.

Examples

Example 1

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

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

Example 2

Input: running_median([7])

Output: [7]

Example 3

Input: running_median([5, 3])

Output: [5, 4]

Hints

Hint 1

Maintain two heaps: a max-heap of the lower half and a min-heap of the upper half, keeping their sizes balanced so they differ by at most 1.

Hint 2

After each insertion, rebalance the heaps so the size difference stays ≤ 1. The median is either the top of the larger heap (odd count) or the average of both tops (even count).

Hint 3

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