Sliding Window · 15 min · free lesson

Sliding Median with Two Heaps: When to Use It

Recognise the problem shape before choosing Sliding Median with Two Heaps.

Core idea

Buried expired entries can otherwise grow beyond O(k) space. State the input preconditions before applying this invariant.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Balance lower and upper heaps while lazily deleting values that leave the window.

O(n log k) time · O(k) space533 execution steps
main · before line 111Initialize a local value

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

Data & variables

Changed Source index
Example input[1,3,-1,-3,5,3,6,7]

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

Call stack · 1 frame
  1. maincall 1

Rust source

Line 111
fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
use std::{
    cmp::Reverse,
    collections::{BinaryHeap, HashMap},
};
#[derive(Default)]
struct MedianWindow {
    low: BinaryHeap<i32>,
    high: BinaryHeap<Reverse<i32>>,
    deleted: HashMap<i32, usize>,
    low_size: usize,
    high_size: usize,
}
impl MedianWindow {
    fn prune(&mut self) {
        while let Some(&x) = self.low.peek() {
            let count = self.deleted.get(&x).copied().unwrap_or(0);
            if count == 0 {
                break;
            }
            if count == 1 {
                self.deleted.remove(&x);
            } else {
                self.deleted.insert(x, count - 1);
            }
            self.low.pop();
        }
        while let Some(&Reverse(x)) = self.high.peek() {
            let count = self.deleted.get(&x).copied().unwrap_or(0);
            if count == 0 {
                break;
            }
            if count == 1 {
                self.deleted.remove(&x);
            } else {
                self.deleted.insert(x, count - 1);
            }
            self.high.pop();
        }
    }
    fn balance(&mut self) {
        self.prune();
        while self.low_size > self.high_size + 1 {
            let x = self.low.pop().unwrap();
            self.low_size -= 1;
            self.high_size += 1;
            self.high.push(Reverse(x));
            self.prune();
        }
        while self.low_size < self.high_size {
            let Reverse(x) = self.high.pop().unwrap();
            self.high_size -= 1;
            self.low_size += 1;
            self.low.push(x);
            self.prune();
        }
    }
    fn add(&mut self, x: i32) {
        self.prune();
        if self.low.peek().is_none_or(|&m| x <= m) {
            self.low.push(x);
            self.low_size += 1;
        } else {
            self.high.push(Reverse(x));
            self.high_size += 1;
        }
        self.balance();
    }
    fn remove(&mut self, x: i32) {
        self.prune();
        if x <= *self.low.peek().unwrap() {
            self.low_size -= 1;
        } else {
            self.high_size -= 1;
        }
        *self.deleted.entry(x).or_default() += 1;
        self.balance();
    }
}
fn sliding_medians(values: &[i32], k: usize) -> Vec<i32> {
    assert!(k > 0 && k % 2 == 1 && k <= values.len());
    let mut state = MedianWindow::default();
    let mut out = Vec::new();
    for i in 0..values.len() {
        state.add(values[i]);
        if i >= k {
            state.remove(values[i - k]);
        }
        // Lazy deletion alone can retain O(n) stale entries. Periodic rebuild
        // bounds storage by O(k), with amortised O(log k) update cost.
        if state.low.len() + state.high.len() > 4 * k {
            state = MedianWindow::default();
            for &x in &values[i + 1 - k..=i] {
                state.add(x);
            }
        }
        if i + 1 >= k {
            state.prune();
            out.push(*state.low.peek().unwrap());
        }
    }
    out
}
 
fn main() {
    let result = csv(sliding_medians(&[1, 3, -1, -3, 5, 3, 6, 7], 3));
    println!("{result}");
}

Try your own version

Compare the visible input `[1,3,-1,-3,5,3,6,7]` with `[3,3,3,3,3,3,3]`. Predict why their results are `1,-1,-1,3,5,6` and `3,3,3,3,3`. Then change one legal value and explain whether the same invariant, buried expired entries can otherwise grow beyond o(k) space, still applies.

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 Sliding Window infographic; panel 5 illustrates Dual Heap Window Median.
Dual Heap Window Median: follow panel 5 to see the operation, then trace the lesson's own example.

Understand it

For windows [1,3,-1], [3,-1,-3], [-1,-3,5], medians are 1,-1,-1. Logical heap sizes exclude delayed removals. Rebuilding from the current k values when physical storage exceeds 4k bounds retained stale entries.

The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Return medians for every odd window of length three. The visible fixture is [1,3,-1,-3,5,3,6,7] and its example result is 1,-1,-1,3,5,6. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.

Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.

String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

A problem is a good match for Sliding Median with Two Heaps when it asks for window medians and percentile-like statistics. Here the concrete task is: Return medians for every odd window of length three. The visible input [1,3,-1,-3,5,3,6,7] is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Choose this family when a valid window can be repaired by moving one boundary; non-monotone constraints may need a different method. The right choice follows from those guarantees, not from a familiar noun in the prompt.

The decisive invariant is: Balance lower and upper heaps while lazily deleting values that leave the window. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? A window is a contiguous interval with a maintained summary. Describe what entering the right edge adds and what leaving the left edge removes. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.

Compare costs before committing. The advertised bound is O(n log k) time · O(k) space; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 1,-1,-1,3,5,6 and explain which part of the state lets the method reach that result.

When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Test an empty window, a window spanning the whole input, and a case where the left edge must advance several times. Represent bounds as a half-open range when possible. Keep counts and the window length in sync when shrinking it. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.

The pattern

Balance lower and upper heaps while lazily deleting values that leave the window.

When to use it: window medians and percentile-like statistics

Complexity: O(n log k) time · O(k) space

Input: [1,3,-1,-3,5,3,6,7]

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(",")
}
use std::{
    cmp::Reverse,
    collections::{BinaryHeap, HashMap},
};
#[derive(Default)]
struct MedianWindow {
    low: BinaryHeap<i32>,
    high: BinaryHeap<Reverse<i32>>,
    deleted: HashMap<i32, usize>,
    low_size: usize,
    high_size: usize,
}
impl MedianWindow {
    fn prune(&mut self) {
        while let Some(&x) = self.low.peek() {
            let count = self.deleted.get(&x).copied().unwrap_or(0);
            if count == 0 {
                break;
            }
            if count == 1 {
                self.deleted.remove(&x);
            } else {
                self.deleted.insert(x, count - 1);
            }
            self.low.pop();
        }
        while let Some(&Reverse(x)) = self.high.peek() {
            let count = self.deleted.get(&x).copied().unwrap_or(0);
            if count == 0 {
                break;
            }
            if count == 1 {
                self.deleted.remove(&x);
            } else {
                self.deleted.insert(x, count - 1);
            }
            self.high.pop();
        }
    }
    fn balance(&mut self) {
        self.prune();
        while self.low_size > self.high_size + 1 {
            let x = self.low.pop().unwrap();
            self.low_size -= 1;
            self.high_size += 1;
            self.high.push(Reverse(x));
            self.prune();
        }
        while self.low_size < self.high_size {
            let Reverse(x) = self.high.pop().unwrap();
            self.high_size -= 1;
            self.low_size += 1;
            self.low.push(x);
            self.prune();
        }
    }
    fn add(&mut self, x: i32) {
        self.prune();
        if self.low.peek().is_none_or(|&m| x <= m) {
            self.low.push(x);
            self.low_size += 1;
        } else {
            self.high.push(Reverse(x));
            self.high_size += 1;
        }
        self.balance();
    }
    fn remove(&mut self, x: i32) {
        self.prune();
        if x <= *self.low.peek().unwrap() {
            self.low_size -= 1;
        } else {
            self.high_size -= 1;
        }
        *self.deleted.entry(x).or_default() += 1;
        self.balance();
    }
}
fn sliding_medians(values: &[i32], k: usize) -> Vec<i32> {
    assert!(k > 0 && k % 2 == 1 && k <= values.len());
    let mut state = MedianWindow::default();
    let mut out = Vec::new();
    for i in 0..values.len() {
        state.add(values[i]);
        if i >= k {
            state.remove(values[i - k]);
        }
        // Lazy deletion alone can retain O(n) stale entries. Periodic rebuild
        // bounds storage by O(k), with amortised O(log k) update cost.
        if state.low.len() + state.high.len() > 4 * k {
            state = MedianWindow::default();
            for &x in &values[i + 1 - k..=i] {
                state.add(x);
            }
        }
        if i + 1 >= k {
            state.prune();
            out.push(*state.low.peek().unwrap());
        }
    }
    out
}

fn main() {
    let result = csv(sliding_medians(&[1, 3, -1, -3, 5, 3, 6, 7], 3));
    println!("{result}");
}

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

Try it

Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.

What success looks like: You can justify the choice from constraints rather than from a remembered problem title.

Check your understanding

Trace Sliding Median with Two Heaps on input [1,2,3,4,5,6,7]. Which result follows from the documented contract?

Reveal the answer
  1. 3,4,5,6
  2. 2,3,4,5,6
  3. 3,3,4,5,6

For this input the result is 2,3,4,5,6. Buried expired entries can otherwise grow beyond O(k) space. Compare this independent fixture with the worked trace: For windows [1,3,-1], [3,-1,-3], [-1,-3,5], medians are 1,-1,-1. Logical heap sizes exclude delayed removals. Rebuilding from the current k values when physical storage exceeds 4k bounds retained stale entries.

Go deeper

Common misconception: “A BinaryHeap loses its ordering after every read”

Buried expired entries can otherwise grow beyond O(k) space. For windows [1,3,-1], [3,-1,-3], [-1,-3,5], medians are 1,-1,-1. Logical heap sizes exclude delayed removals. Rebuilding from the current k values when physical storage exceeds 4k bounds retained stale entries.

  1. Concrete transition: For windows [1,3,-1], [3,-1,-3], [-1,-3,5], medians are 1,-1,-1. Logical heap sizes exclude delayed removals. Rebuilding from the current k values when physical storage exceeds 4k bounds retained stale entries.
  2. Independent second fixture: Input [1,2,3,4,5,6,7] produces 2,3,4,5,6. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation.
  3. Boundary and contract: Input [8,7,6,5,4,3,2] produces 7,6,5,4,3. Buried expired entries can otherwise grow beyond O(k) space. The stated work bound is O(n log k) time · O(k) space. Count actual state changes; a successful output test alone does not prove that bound.

Transfer challenge: Compare the visible input [1,3,-1,-3,5,3,6,7] with [3,3,3,3,3,3,3]. Predict why their results are 1,-1,-1,3,5,6 and 3,3,3,3,3. Then change one legal value and explain whether the same invariant, buried expired entries can otherwise grow beyond o(k) space, still applies.

Connections

  • Sliding Median with Two Heaps: Mental Model: Balance lower and upper heaps while lazily deleting values that leave the window.
  • Challenge: Sliding Median with Two Heaps: Return medians for every odd window of length three.
Reveal the Algorithm Atlas answer

1,-1,-1,3,5,6

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: Sliding Median with Two Heaps: When to Use It (courseId "algorithms", lessonId "algorithm.dual-heap-window-median.recognize")
Link: https://crabrix.com/learn/algorithms/algorithm.dual-heap-window-median.recognize
Goal: Buried expired entries can otherwise grow beyond O(k) space. State the input preconditions before applying this invariant.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.dual-heap-window-median.recognize) 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.