Two balanced heaps

Report the Middle Sensor Reading

Original & variantFind Median from Data Stream ↗

Return the median after every arriving reading, rather than exposing an interactive class.

01. The question

Sensor readings arrive one at a time. Return the median after every arrival. For an even number of readings, average the two middle values; keep duplicate readings as separate observations.

Before revealing the idea, predict the result and describe what information you would need to track.

02. Worked example

Inputreadings = [7, 2, 10, 4]

Output[7, 4.5, 7, 5.5]

  1. After 7 the median is 7.
  2. After 2 the middle pair is 2 and 7, giving 4.5.
  3. After 10 the median is 7; after 4 it is (4 + 7) / 2 = 5.5.

Try your code

Define solve(data, parameter="") and return your result. Your code runs locally, not on a server.

Edit your test cases

Use 1-10 objects with data and an optional string parameter. Expected outputs are computed from the lesson. An optional expected field must be correct.

Input contract & reference code

Example data: [7,2,10,4]. Parameter: "". Numeric parameters arrive as strings; convert them with int(parameter) when needed.

The example and generated cases use the question’s exact variant. This checks behavior on a small test batch—not performance on every possible input.

Python runtime notices

Python downloads only when you run code, using compressed runtime assets. Code is not saved or uploaded. Enable JavaScript to run it.

Five-second execution limit per batch. Standard-library Python only; additional packages and network access are unavailable. Stop ends execution without blocking the lesson.

03. The idea

Try sketching your own approach first. What would you track, and why would it work?

Reveal the idea
  1. Keep the lower half in a max-heap, represented by negative values in Python.
  2. Move its largest value into the upper min-heap, then rebalance the sizes.
  3. Read the lower root for odd counts, or average both roots for even counts.

04. Watch it happen

Use Step to move slowly, or Play to follow the whole trace. Change a preset or load your own input.

Input & settings

0-20 integers, each -1,000 to 1,000. Return one median per arrival.

Red = current item / blue = active window or cells / green = completed work. A value docks at its actual destination; the original input stays unchanged. Positions start at 0.

Working state / what changes

Ready to begin

Enable JavaScript to step through the animation. The worked example and solution below remain readable without it.

Python / why it changes

The line behind the step

import heapq

def solve(readings, parameter=""):
    lower, upper, medians = [], [], []
    for value in readings:
        heapq.heappush(lower, -value)
        heapq.heappush(upper, -heapq.heappop(lower))
        if len(upper) > len(lower):
            heapq.heappush(lower, -heapq.heappop(upper))
        if len(lower) > len(upper):
            median = -lower[0]
        else:
            median = (-lower[0] + upper[0]) / 2
        medians.append(median)
    return medians
How to use this walkthrough

Hover or focus a control for its label. Play forms the input and follows values into the working state. Step shows one change; Back and the slider restore exact snapshots. Reduced motion uses instant updates. Saved snapshots and sorted heap displays are teaching overhead, not algorithm complexity.

05. Python solution

import heapq

def solve(readings, parameter=""):
    lower, upper, medians = [], [], []
    for value in readings:
        heapq.heappush(lower, -value)
        heapq.heappush(upper, -heapq.heappop(lower))
        if len(upper) > len(lower):
            heapq.heappush(lower, -heapq.heappop(upper))
        if len(lower) > len(upper):
            median = -lower[0]
        else:
            median = (-lower[0] + upper[0]) / 2
        medians.append(median)
    return medians

06. Cost & edge cases

Time
O(n log(n + 1)) for all insertions; O(1) for each median query
Space
O(n)
  • An empty stream returns [].
  • Equal values are separate readings.
  • Negative readings and half-integer medians are supported. The displayed priority lists show next-pop order, not the heap array.

Keep going