Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Closest Pair of Points Implementation in Rust

19 min readadvanced
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Closest Pair of Points runs in O(n log n) time and O(n) space, in Rust as in every other language.
  • ✓f64 carries hypot, powi, INFINITY and total_cmp, the last giving the IEEE 754 total order that sorting coordinates needs.
  • ✓sort_by_key(|p| p.y) does not compile here: the key type must be Ord and f64 is only PartialOrd.
  • ✓The Rust trap: The borrow checker is what makes this algorithm awkward in Rust and in none of the other seven.
  • ✓Indexing strip[j] inside the successor scan emits a bounds check per access; strip[i + 1..].iter().take_while(..) gives the optimiser the same information with no unsafe.

What Closest Pair of Points actually is

Given n points in the plane, the closest pair is the two with the smallest Euclidean distance between them. Brute force is O(n^2); the divide-and-conquer solution sorts by x, splits at the median, recurses on both halves, then repairs the boundary by scanning a vertical strip of width 2d ordered by y, where each point only has to be compared with a constant number of successors. Working engineers reach for it in collision detection, de-duplicating GPS fixes, seeding clusters and validating meshes, usually as the exact check sitting behind a spatial index.

Closest Pair of Points in Rust: what you actually reach for

f64 carries hypot, powi, INFINITY and total_cmp, the last giving the IEEE 754 total order that sorting coordinates needs. Slices give sort_unstable_by (pattern-defeating quicksort, no allocation) and sort_by (stable, allocates scratch), plus split_at and split_at_mut to hand out the two halves without copying, and windows for the successor scan. std::cmp::Ordering is the comparator result. Nothing in std does spatial indexing; when the exact pair is only step one, the crates people land on are rstar or kiddo.

Rust implementation

sort_by_key(|p| p.y) does not compile here: the key type must be Ord and f64 is only PartialOrd. Reviewers then reject the usual workaround a.y.partial_cmp(&b.y).unwrap(), because a single NaN coordinate turns it into a panic, and ask for a.y.total_cmp(&b.y) or an ordered_float::OrderedFloat newtype. They also want #[derive(Clone, Copy)] on a 16-byte Point so it moves freely, split_at instead of two to_vec() calls, and squared distances so sqrt never appears in the inner loop.
rust
#[derive(Clone, Copy, Debug)]
pub struct Point { pub x: f64, pub y: f64 }

fn d2(a: Point, b: Point) -> f64 {
    let (dx, dy) = (a.x - b.x, a.y - b.y);
    dx * dx + dy * dy
}

/// Returns the distance of the closest pair (`f64::INFINITY` for fewer than 2 points).
pub fn closest_pair(pts: &[Point]) -> f64 {
    let mut px = pts.to_vec();
    px.sort_unstable_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));
    solve(&px).0.sqrt()   // the one sqrt, outside every loop
}

// returns (best squared distance, the same points ordered by y)
fn solve(px: &[Point]) -> (f64, Vec<Point>) {
    let n = px.len();
    if n <= 3 {
        let mut best = f64::INFINITY;
        for i in 0..n {
            for j in i + 1..n {
                best = best.min(d2(px[i], px[j]));
            }
        }
        let mut ys = px.to_vec();
        ys.sort_unstable_by(|a, b| a.y.total_cmp(&b.y));
        return (best, ys);
    }
    let mid = n / 2;
    let split = px[mid].x;
    let (lx, rx) = px.split_at(mid);
    let (lb, ly) = solve(lx);
    let (rb, ry) = solve(rx);
    let mut best = lb.min(rb);
    let mut ys = Vec::with_capacity(n);
    let (mut i, mut j) = (0usize, 0usize);
    while i < ly.len() || j < ry.len() {
        if j == ry.len() || (i < ly.len() && ly[i].y <= ry[j].y) {
            ys.push(ly[i]);
            i += 1;
        } else {
            ys.push(ry[j]);
            j += 1;
        }
    }
    let strip: Vec<Point> = ys
        .iter()
        .copied()
        .filter(|p| (p.x - split) * (p.x - split) < best)
        .collect();
    // an index loop, not take_while: that closure borrows `best` for the whole
    // loop body while the body assigns to it - error[E0506].
    for k in 0..strip.len() {
        let p = strip[k];
        for &q in &strip[k + 1..] {
            let dy = q.y - p.y;
            if dy * dy >= best {
                break;
            }
            best = best.min(d2(p, q));
        }
    }
    (best, ys)
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Rust-specific trap

The borrow checker is what makes this algorithm awkward in Rust and in none of the other seven. The textbook version keeps one y-sorted scratch buffer and hands overlapping windows of it to both recursive calls - two &mut into the same Vec, which will not compile. split_at_mut solves the disjoint case, but the merge step wants to read both halves while writing the parent range of that same buffer, so you need either two buffers alternating per level or an owned Vec returned upward. Reaching for RefCell compiles and then panics at runtime with already borrowed: BorrowMutError on the second borrow_mut - the mirror-image already mutably borrowed: BorrowError is what a plain borrow() gets while the mutable one is still live.

Performance in Rust, beyond the O(n log n)

Indexing strip[j] inside the successor scan emits a bounds check per access; strip[i + 1..].iter().take_while(..) gives the optimiser the same information with no unsafe. sort_unstable_by avoids the roughly n/2 element scratch that sort_by allocates, and the comparator is monomorphised and inlined, so there is no indirect call per comparison the way there is behind a Go func value or a Java Comparator. f64::hypot rescales to avoid overflow; comparing squared distances skips it entirely. No GC, so the only allocations are the ones you wrote. The asymptotic cost is the same in every language, O(n log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Closest Pair of Points between languages.

Real-World Applications

Closest Pair of Points applies wherever its problem shape appears in your own code. In Rust, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Closest Pair of Points helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Closest Pair of Points appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Closest Pair of Points over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Closest Pair of Points to build pattern recognition. In Rust, demonstrate proficiency with ownership system and pattern matching to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Rust code that is both correct and maintainable.

Frequently Asked Questions

Which Rust type or library should I use for Closest Pair of Points?

f64 carries hypot, powi, INFINITY and total_cmp, the last giving the IEEE 754 total order that sorting coordinates needs. Slices give sort_unstable_by (pattern-defeating quicksort, no allocation) and sort_by (stable, allocates scratch), plus split_at and split_at_mut to hand out the two halves without copying, and windows for the successor scan. std::cmp::Ordering is the comparator result. Nothing in std does spatial indexing; when the exact pair is only step one, the crates people land on are rstar or kiddo.

What is the most common Rust mistake when implementing Closest Pair of Points?

The borrow checker is what makes this algorithm awkward in Rust and in none of the other seven. The textbook version keeps one y-sorted scratch buffer and hands overlapping windows of it to both recursive calls - two &mut into the same Vec, which will not compile. split_at_mut solves the disjoint case, but the merge step wants to read both halves while writing the parent range of that same buffer, so you need either two buffers alternating per level or an owned Vec returned upward. Reaching for RefCell compiles and then panics at runtime with already borrowed: BorrowMutError on the second borrow_mut - the mirror-image already mutably borrowed: BorrowError is what a plain borrow() gets while the mutable one is still live.

How does Closest Pair of Points actually perform in Rust?

Indexing strip[j] inside the successor scan emits a bounds check per access; strip[i + 1..].iter().take_while(..) gives the optimiser the same information with no unsafe. sort_unstable_by avoids the roughly n/2 element scratch that sort_by allocates, and the comparator is monomorphised and inlined, so there is no indirect call per comparison the way there is behind a Go func value or a Java Comparator. f64::hypot rescales to avoid overflow; comparing squared distances skips it entirely. No GC, so the only allocations are the ones you wrote. Time complexity is O(n log n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Before paying for Devin, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.