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

Convex Hull 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

  • ✓Convex Hull runs in O(n log n) time and O(n) space, in Rust as in every other language.
  • ✓std has no geometry. The hull is a Vec<Point> over a #[derive(Clone, Copy)] struct plus slice::sort_unstable_by; for float coordinates f64::total_cmp gives the total order sort_by wants, because f64 itself is only PartialOrd and therefore has no plain sort().
  • ✓The signature reviewers want is fn convex_hull(points: &[Point]) -> Vec<Point>: borrow the input, own the output, never take Vec<Point> by value just to sort it.
  • ✓The Rust trap: Rust is the only language here where the same arithmetic behaves differently in your tests and in your shipped binary.
  • ✓The snippet below is the plain form, and two of these are the tuning it leaves on the table.

What Convex Hull actually is

The convex hull of a point set is the smallest convex polygon containing every point: the shape a rubber band snaps to. The divide-and-conquer form sorts by x, hulls each half recursively, then stitches the halves with an upper and a lower tangent in linear time, giving O(n log n) worst case. Quickhull is the other divide step (average O(n log n), worst O(n^2)). Engineers reach for a hull in collision broad-phase, GIS footprints, outlier boundaries, and as step one of rotating calipers for diameter, min-width and min-area rectangle. Andrew's monotone chain -- sort once, then two linear scans -- hits the same bound with a far simpler merge, and is what most production code actually ships.

Convex Hull in Rust: what you actually reach for

std has no geometry. The hull is a Vec<Point> over a #[derive(Clone, Copy)] struct plus slice::sort_unstable_by; for float coordinates f64::total_cmp gives the total order sort_by wants, because f64 itself is only PartialOrd and therefore has no plain sort(). The ecosystem answer is the geo crate: use geo::ConvexHull; brings a trait implemented for MultiPoint, LineString and Polygon, and .convex_hull() returns a Polygon<T> whose exterior ring is closed. geo-types supplies the Coord and Point primitives that the whole Rust geo stack shares, so you rarely define your own once geo is in the tree.

Rust implementation

The signature reviewers want is fn convex_hull(points: &[Point]) -> Vec<Point>: borrow the input, own the output, never take Vec<Point> by value just to sort it. Point derives Clone, Copy, PartialEq so the pop loop moves sixteen bytes instead of juggling borrows. sort_unstable_by is preferred over sort_by here because the order of equal points is irrelevant and the stable sort allocates. .partial_cmp(..).unwrap() on floats is rejected outright: use total_cmp, or integer coordinates.
rust
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct Point {
    pub x: i64,
    pub y: i64,
}

#[inline]
fn cross(o: Point, a: Point, b: Point) -> i128 {
    // Widen: an i64 product here overflows, which panics in debug and
    // wraps silently in release.
    let (ax, ay) = (a.x as i128 - o.x as i128, a.y as i128 - o.y as i128);
    let (bx, by) = (b.x as i128 - o.x as i128, b.y as i128 - o.y as i128);
    ax * by - ay * bx
}

fn chain(pts: impl Iterator<Item = Point>) -> Vec<Point> {
    let mut h: Vec<Point> = Vec::new();
    for p in pts {
        while h.len() >= 2 {
            let n = h.len();
            if cross(h[n - 2], h[n - 1], p) > 0 {
                break;
            }
            h.pop();
        }
        h.push(p);
    }
    h.pop();
    h
}

pub fn convex_hull(points: &[Point]) -> Vec<Point> {
    let mut pts = points.to_vec();
    pts.sort_unstable();
    pts.dedup();
    if pts.len() < 3 {
        return pts;
    }
    let mut hull = chain(pts.iter().copied());
    hull.extend(chain(pts.iter().rev().copied()));
    hull
}

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

Rust is the only language here where the same arithmetic behaves differently in your tests and in your shipped binary. (a.x - o.x) * (b.y - o.y) on i32 or i64 overflows for large coordinates, and because overflow-checks defaults to following debug-assertions, that is a panic -- attempt to multiply with overflow -- under cargo test, and a silent two's-complement wrap under cargo build --release. So the failing input aborts loudly in CI and quietly returns a mangled hull in production, which is the wrong way round. Widen the predicate to i128, or use checked_mul, or set overflow-checks = true on the release profile.

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

The snippet below is the plain form, and two of these are the tuning it leaves on the table. h[h.len() - 2] emits two bounds checks per iteration that LLVM often cannot elide, so swap the index pair for a slice pattern -- while let [.., a, b] = &h[..] { if cross(*a, *b, p) > 0 { break; } h.pop(); } -- or reach for last(). And Vec::new() grows by doubling, so Vec::with_capacity(points.len()) removes every reallocation in the scan. sort_unstable_by is pattern-defeating quicksort done in place with no scratch buffer, while the stable sort_by allocates temporary space proportional to the input. Vec::pop is a length decrement and nothing else. A Copy sixteen-byte Point stays in registers once cross inlines; behind a Box it would not. 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 Convex Hull between languages.

Real-World Applications

Convex Hull 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 Convex Hull helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Convex Hull 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 Convex Hull 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 Convex Hull 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 Convex Hull?

std has no geometry. The hull is a Vec<Point> over a #[derive(Clone, Copy)] struct plus slice::sort_unstable_by; for float coordinates f64::total_cmp gives the total order sort_by wants, because f64 itself is only PartialOrd and therefore has no plain sort(). The ecosystem answer is the geo crate: use geo::ConvexHull; brings a trait implemented for MultiPoint, LineString and Polygon, and .convex_hull() returns a Polygon<T> whose exterior ring is closed. geo-types supplies the Coord and Point primitives that the whole Rust geo stack shares, so you rarely define your own once geo is in the tree.

What is the most common Rust mistake when implementing Convex Hull?

Rust is the only language here where the same arithmetic behaves differently in your tests and in your shipped binary. (a.x - o.x) * (b.y - o.y) on i32 or i64 overflows for large coordinates, and because overflow-checks defaults to following debug-assertions, that is a panic -- attempt to multiply with overflow -- under cargo test, and a silent two's-complement wrap under cargo build --release. So the failing input aborts loudly in CI and quietly returns a mangled hull in production, which is the wrong way round. Widen the predicate to i128, or use checked_mul, or set overflow-checks = true on the release profile.

How does Convex Hull actually perform in Rust?

The snippet below is the plain form, and two of these are the tuning it leaves on the table. h[h.len() - 2] emits two bounds checks per iteration that LLVM often cannot elide, so swap the index pair for a slice pattern -- while let [.., a, b] = &h[..] { if cross(*a, *b, p) > 0 { break; } h.pop(); } -- or reach for last(). And Vec::new() grows by doubling, so Vec::with_capacity(points.len()) removes every reallocation in the scan. sort_unstable_by is pattern-defeating quicksort done in place with no scratch buffer, while the stable sort_by allocates temporary space proportional to the input. Vec::pop is a length decrement and nothing else. A Copy sixteen-byte Point stays in registers once cross inlines; behind a Box it would not. 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

Most AI and dev tools have a student plan. See which ones and how to claim them 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.