Heaps & Streaming · 15 min · free lesson

Challenge: Bounded Heap for K Closest

Return the two points closest to the origin, ordered by distance then coordinates.

Core idea

Squaring preserves the ordering of nonnegative distances. Return the two points closest to the origin, ordered by distance then coordinates.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Keep the worst current winner at the root so a better candidate replaces it.

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

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

Data & variables

Changed Source index
Example input[(0,1),(2,0),(0,3)]

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

Call stack · 1 frame
  1. maincall 1

Rust source

Line 16
fn closest(points: &[(i32, i32)], k: usize) -> Vec<(i32, i32)> {
    let mut heap = std::collections::BinaryHeap::new();
    for &(x, y) in points {
        let distance = i64::from(x) * i64::from(x) + i64::from(y) * i64::from(y);
        heap.push((distance, x, y));
        if heap.len() > k {
            heap.pop();
        }
    }
    let mut selected = heap.into_vec();
    selected.sort_unstable();
    selected.into_iter().map(|(_, x, y)| (x, y)).collect()
}
 
fn main() {
    let result = closest(&[(0, 1), (2, 0), (0, 3)], 2)
        .iter()
        .map(|(x, y)| format!("{x}:{y}"))
        .collect::<Vec<_>>()
        .join(",");
    println!("{result}");
}

Try your own version

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

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. Borrowed or moved values are hidden when they cannot be inspected safely.
Five-panel Heaps & Streaming infographic; panel 5 illustrates Closest K Heap.
Closest K Heap: follow panel 5 to see the operation, then trace the lesson's own example.

Understand it

Squaring preserves the ordering of nonnegative distances. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input [(0,1),(2,0),(0,3)], the worked program returns 0:1,2:0. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input [(1,3),(-2,2),(2,-2),(5,1)]; predict that result before opening the answer reveal. The precise contract is: Return the two points closest to the origin, ordered by distance then coordinates.

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 two points closest to the origin, ordered by distance then coordinates. On input [(1,3),(-2,2),(2,-2),(5,1)], 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 worst current winner at the root so a better candidate replaces it. 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(n log k) time · O(k) 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 worst current winner at the root so a better candidate replaces it.

When to use it: nearest points, closest values, approximate neighbors

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

Input: [(1,3),(-2,2),(2,-2),(5,1)]

Read the code

fn closest(points: &[(i32, i32)], k: usize) -> Vec<(i32, i32)> {
    let mut heap = std::collections::BinaryHeap::new();
    for &(x, y) in points {
        let distance = i64::from(x) * i64::from(x) + i64::from(y) * i64::from(y);
        heap.push((distance, x, y));
        if heap.len() > k {
            heap.pop();
        }
    }
    let mut selected = heap.into_vec();
    selected.sort_unstable();
    selected.into_iter().map(|(_, x, y)| (x, y)).collect()
}

fn main() {
    let result = closest(&[(0, 1), (2, 0), (0, 3)], 2)
        .iter()
        .map(|(x, y)| format!("{x}:{y}"))
        .collect::<Vec<_>>()
        .join(",");
    println!("{result}");
}

Complete std-only closest-k-heap 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 two points closest to the origin, ordered by distance then coordinates.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement closest-k-heap")
}

Try it

Return the two points closest to the origin, ordered by distance then coordinates.

What success looks like: The private harness prints PASS closest-k-heap. 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 closest-k-heap: with input [(3,4),(0,2),(2,0)], what result should solve return?

Reveal the answer
  1. 0:2,2:0
  2. 2:0,0:2
  3. 3:4,0:2

For this input the result is 0:2,2:0. Squaring preserves the ordering of nonnegative distances. Compare this independent fixture with the worked trace: Points (-2,2) and (2,-2) both have squared distance 8, smaller than (1,3) at 10. The explicit coordinate tie break orders -2:2 before 2:-2. A bounded max-heap discards the farthest retained candidate.

Go deeper

Common misconception: “Squared distance always equals ordinary distance”

Squaring preserves the ordering of nonnegative distances. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: Squaring preserves the ordering of nonnegative distances. 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 [(0,1),(2,0),(0,3)] and computes 0:1,2:0. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For [(3,4),(0,2),(2,0)], the independently calculated result is 0:2,2:0. The complexity discussion uses O(n log k) time · O(k) space. Verify the state invariant before reasoning about the operation count.

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

Connections

  • Bounded Heap for K Closest: When to Use It: nearest points, closest values, approximate neighbors
  • Median from Two Heaps: Mental Model: Keep the lower half in a max-heap and upper half in a min-heap with sizes differing by at most one.
Reveal the Algorithm Atlas answer

-2:2,2:-2

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: Bounded Heap for K Closest (courseId "algorithms", lessonId "algorithm.closest-k-heap.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.closest-k-heap.challenge
Goal: Squaring preserves the ordering of nonnegative distances. Return the two points closest to the origin, ordered by distance then coordinates.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.closest-k-heap.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.