Heaps & Streaming · 15 min · free lesson

Challenge: Median from Two Heaps

Return the running median after each inserted value.

Core idea

The lower half has either the same size as the upper half or one extra item. Return the running median after each inserted value.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Keep the lower half in a max-heap and upper half in a min-heap with sizes differing by at most one.

O(log n) insert · O(1) median · O(n) space25 execution steps
main · before line 33Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example input[1,3]

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 33
fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
fn stream_medians(values: &[i32]) -> Vec<f64> {
    let mut low = std::collections::BinaryHeap::new();
    let mut high = std::collections::BinaryHeap::new();
    let mut out = Vec::new();
    for &x in values {
        if low.peek().is_none_or(|&m| x <= m) {
            low.push(x);
        } else {
            high.push(std::cmp::Reverse(x));
        }
        if low.len() > high.len() + 1 {
            high.push(std::cmp::Reverse(low.pop().unwrap()));
        }
        if high.len() > low.len() {
            low.push(high.pop().unwrap().0);
        }
        out.push(if low.len() == high.len() {
            (*low.peek().unwrap() as f64 + high.peek().unwrap().0 as f64) / 2.0
        } else {
            *low.peek().unwrap() as f64
        });
    }
    out
}
 
fn main() {
    let result = csv(stream_medians(&[1, 3]));
    println!("{result}");
}

Try your own version

Change the independent fixture `[1,3]` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `[5,2,10,4]`.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel Heaps & Streaming infographic; panel 1 illustrates Two Heap Median.
Two Heap Median: follow panel 1 to see the operation, then trace this lesson's example.

Understand it

The lower half has either the same size as the upper half or one extra item. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input [1,3], the worked program returns 1,2. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input [5,2,10,4]; predict that result before opening the answer reveal. The precise contract is: Return the running median after each inserted value.

Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

Solve the exact task, not just the visible example: Return the running median after each inserted value. On input [5,2,10,4], predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.

Build the solution around one maintained claim: Keep the lower half in a max-heap and upper half in a min-heap with sizes differing by at most one. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. A heap keeps the current extremum accessible while new items arrive. Explain what belongs in the heap and what may be discarded. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.

Check both correctness and cost. The intended bound is O(log n) insert · O(1) median · O(n) space; explain which operation dominates it and how many times the input can trigger that operation. Check an empty stream, k equal to zero or to the input length, duplicate priorities, and stale entries if deletion is lazy. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.

The pattern

Keep the lower half in a max-heap and upper half in a min-heap with sizes differing by at most one.

When to use it: online medians and percentile pivots

Complexity: O(log n) insert · O(1) median · O(n) space

Input: [5,2,10,4]

Read the code

fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
fn stream_medians(values: &[i32]) -> Vec<f64> {
    let mut low = std::collections::BinaryHeap::new();
    let mut high = std::collections::BinaryHeap::new();
    let mut out = Vec::new();
    for &x in values {
        if low.peek().is_none_or(|&m| x <= m) {
            low.push(x);
        } else {
            high.push(std::cmp::Reverse(x));
        }
        if low.len() > high.len() + 1 {
            high.push(std::cmp::Reverse(low.pop().unwrap()));
        }
        if high.len() > low.len() {
            low.push(high.pop().unwrap().0);
        }
        out.push(if low.len() == high.len() {
            (*low.peek().unwrap() as f64 + high.peek().unwrap().0 as f64) / 2.0
        } else {
            *low.peek().unwrap() as f64
        });
    }
    out
}

fn main() {
    let result = csv(stream_medians(&[1, 3]));
    println!("{result}");
}

Complete std-only two-heap-median program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Practice starter

pub fn solve(input: &str) -> String {
    // Return the running median after each inserted value.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement two-heap-median")
}

Try it

Return the running median after each inserted value.

What success looks like: The private harness prints PASS two-heap-median. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.

Check your understanding

Boundary check for two-heap-median: with input [8,7,6,5,4,3,2], what result should solve return?

Reveal the answer
  1. 8,7.5,7,6.5,6,5.5,5
  2. 8,7,7,6,6,5,5
  3. 8,8,7,7,6,6,5

For this input the result is 8,7.5,7,6.5,6,5.5,5. The lower half has either the same size as the upper half or one extra item. Compare this independent fixture with the worked trace: For [5,2,10,4], medians are 5,3.5,5,4.5. Rebalance after each insertion so the lower maximum and upper minimum border the middle; promote to f64 before adding the two middle values.

Go deeper

Common misconception: “Both heaps must contain every observation”

The lower half has either the same size as the upper half or one extra item. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: The lower half has either the same size as the upper half or one extra item. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
  2. Independent typed fixture: The worked call uses [1,3] and computes 1,2. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For [8,7,6,5,4,3,2], the independently calculated result is 8,7.5,7,6.5,6,5.5,5. The complexity discussion uses O(log n) insert · O(1) median · O(n) space. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture [1,3] in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge [5,2,10,4].

Connections

  • Median from Two Heaps: When to Use It: online medians and percentile pivots
  • Lazy Heap Deletion: Mental Model: Record invalidated values separately and discard stale roots only when they surface.
Reveal the Algorithm Atlas answer

5,3.5,5,4.5

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Challenge: Median from Two Heaps (courseId "algorithms", lessonId "algorithm.two-heap-median.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.two-heap-median.challenge
Goal: The lower half has either the same size as the upper half or one extra item. Return the running median after each inserted value.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.two-heap-median.challenge) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.