Python coding

Median after each new number

Numbers arrive one at a time in the list nums. Return a list of the same length where item i is the median of the first i + 1 numbers. The median is the middle value once they are sorted; with an even count it is the mean of the two middle values, so it can end in .5 (whole medians pass as 4 or 4.0).

Values may repeat and may be negative. Aim for O(log n) per number instead of re-sorting each prefix.

Besides the tests, one large input (4,000 numbers) with a ~300 ms limit (scaled to your device's speed): brute force won't pass.

  • running_medians([5,3,8,1]) → [5,4,5,4]
  • running_medians([2,7]) → [2,4.5]
  • running_medians([1,2,3,4,5]) → [1,1.5,2,2.5,3]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Only the middle matters. Split the numbers seen so far into a smaller half and a larger half; the median sits where the two halves meet.

Hint 2

Keep the smaller half in a max-heap (negate the values for heapq) and the larger half in a min-heap. Their roots are the two middle values.

Hint 3

Route every number through one heap into the other, then rebalance so the sizes differ by at most one; inserting by comparison alone lets one half outgrow the other.

Solution and why it works
pythonO(n log n) · O(n)
import heapq


def running_medians(nums: list[int]) -> list[float]:
    low, high = [], []       # max-heap (negated) of the smaller half, min-heap of the larger
    medians = []
    for x in nums:
        heapq.heappush(low, -x)
        heapq.heappush(high, -heapq.heappop(low))        # the largest of low moves up
        if len(high) > len(low):
            heapq.heappush(low, -heapq.heappop(high))    # low keeps the extra item
        medians.append(-low[0] if len(low) > len(high) else (high[0] - low[0]) / 2)
    return medians

The max-heap low holds the smaller half and the min-heap high the larger, so both middle values are always at a root and each number costs O(log n). Pushing into low, moving its largest to high, then moving one back if high is bigger keeps two invariants: everything in low ≤ everything in high, and low has the same size or one more. Traps: skipping the rebalance, forgetting to negate for the max-heap, and //, which rounds 2.5 down.