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

Closest Pair of Points Implementation in Go

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 Go as in every other language.
  • ✓math.Hypot, math.Inf(1) and math.MaxFloat64 give the arithmetic and the bound. slices.SortFunc together with cmp.Compare, both from the standard-library slices and cmp packages, give the two orderings, and slices.Clone gives the working copy.
  • ✓slices.SortFunc(px, func(a, b Point) int { return cmp.Compare(a.X, b.X) }) rather than sort.Slice - it is generic, skips the reflect-based swapper, and cmp.Compare orders NaN deterministically instead of leaving it to a < that is false in both directions.
  • ✓The Go trap: Subslices share one backing array, and this algorithm splits and then appends - the exact shape that corrupts data in Go and in none of the other seven.
  • ✓A []Point of plain float64 structs holds no pointers, so the garbage collector skips scanning it entirely - the large constant-factor win over []*Point.

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 Go: what you actually reach for

math.Hypot, math.Inf(1) and math.MaxFloat64 give the arithmetic and the bound. slices.SortFunc together with cmp.Compare, both from the standard-library slices and cmp packages, give the two orderings, and slices.Clone gives the working copy. sort.Slice still works and takes a less func(i, j int) bool, but it drives the swap through reflection. There is no point type and no spatial index in the standard library: type Point struct{ X, Y float64 } and a plain []Point is the entire data model.

Go implementation

slices.SortFunc(px, func(a, b Point) int { return cmp.Compare(a.X, b.X) }) rather than sort.Slice - it is generic, skips the reflect-based swapper, and cmp.Compare orders NaN deterministically instead of leaving it to a < that is false in both directions. Reviewers want subslices px[:mid] instead of copies, results returned as multiple values instead of through a *Result, and a scratch buffer reused with buf = append(buf[:0], ...) rather than a fresh make at every recursion level.
go
package geom

import (
	"cmp"
	"math"
	"slices"
)

type Point struct{ X, Y float64 }

func d2(a, b Point) float64 {
	dx, dy := a.X-b.X, a.Y-b.Y
	return dx*dx + dy*dy
}

// Closest returns the squared distance of the closest pair.
func Closest(pts []Point) float64 {
	px := slices.Clone(pts)
	slices.SortFunc(px, func(a, b Point) int { return cmp.Compare(a.X, b.X) })
	best, _ := solve(px)
	return best
}

// solve also returns px re-ordered by Y.
func solve(px []Point) (float64, []Point) {
	n := len(px)
	ys := slices.Clone(px)
	if n <= 3 {
		best := math.Inf(1)
		for i := range px {
			for j := i + 1; j < n; j++ {
				best = math.Min(best, d2(px[i], px[j]))
			}
		}
		slices.SortFunc(ys, func(a, b Point) int { return cmp.Compare(a.Y, b.Y) })
		return best, ys
	}
	mid := n / 2
	split := px[mid].X
	// px[:mid:mid] caps the capacity so no append can reach the right half.
	lb, ly := solve(px[:mid:mid])
	rb, ry := solve(px[mid:])
	best := math.Min(lb, rb)
	ys = ys[:0]
	i, j := 0, 0
	for i < len(ly) || j < len(ry) {
		if j == len(ry) || (i < len(ly) && ly[i].Y <= ry[j].Y) {
			ys = append(ys, ly[i])
			i++
		} else {
			ys = append(ys, ry[j])
			j++
		}
	}
	var strip []Point
	for _, p := range ys {
		if dx := p.X - split; dx*dx < best {
			strip = append(strip, p)
		}
	}
	for k, p := range strip {
		for m := k + 1; m < len(strip); m++ {
			if dy := strip[m].Y - p.Y; dy*dy >= best {
				break
			}
			best = math.Min(best, d2(p, strip[m]))
		}
	}
	return 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 Go-specific trap

Subslices share one backing array, and this algorithm splits and then appends - the exact shape that corrupts data in Go and in none of the other seven. left := px[:mid] inherits cap(px), so an append while merging the y-order writes straight over px[mid], which is the first element of the right half you have not recursed into yet. The result comes back finite and wrong, and no test with three points reproduces it. Cut the capacity at the split with the three-index form px[:mid:mid], or merge into a buffer you allocated and never append to a slice you were handed.

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

A []Point of plain float64 structs holds no pointers, so the garbage collector skips scanning it entirely - the large constant-factor win over []*Point. sort.Slice pays a reflect-driven swap plus an indirect closure call per comparison; slices.SortFunc drops the reflection but the comparison is still an indirect call through a func value, so declaring the comparator once outside the recursion matters. math.Hypot is a real call and is not inlined, while dx*dx + dy*dy is. Returning a pointer from the recursion makes the value escape to the heap. 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 Go, 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 Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

Frequently Asked Questions

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

math.Hypot, math.Inf(1) and math.MaxFloat64 give the arithmetic and the bound. slices.SortFunc together with cmp.Compare, both from the standard-library slices and cmp packages, give the two orderings, and slices.Clone gives the working copy. sort.Slice still works and takes a less func(i, j int) bool, but it drives the swap through reflection. There is no point type and no spatial index in the standard library: type Point struct{ X, Y float64 } and a plain []Point is the entire data model.

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

Subslices share one backing array, and this algorithm splits and then appends - the exact shape that corrupts data in Go and in none of the other seven. left := px[:mid] inherits cap(px), so an append while merging the y-order writes straight over px[mid], which is the first element of the right half you have not recursed into yet. The result comes back finite and wrong, and no test with three points reproduces it. Cut the capacity at the split with the three-index form px[:mid:mid], or merge into a buffer you allocated and never append to a slice you were handed.

How does Closest Pair of Points actually perform in Go?

A []Point of plain float64 structs holds no pointers, so the garbage collector skips scanning it entirely - the large constant-factor win over []*Point. sort.Slice pays a reflect-driven swap plus an indirect closure call per comparison; slices.SortFunc drops the reflection but the comparison is still an indirect call through a func value, so declaring the comparator once outside the recursion matters. math.Hypot is a real call and is not inlined, while dx*dx + dy*dy is. Returning a pointer from the recursion makes the value escape to the heap. 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

If you are a student, see what Devin offers students for free 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.