Closest Pair of Points Implementation in Go
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
Closest Pair of Points in Go: what you actually reach for
Go implementation
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 FreeThe Go-specific trap
Performance in Go, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
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).
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 trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.