Find K nearest Points to Point P in 2-dimensional plane
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
To find the k nearest points to a target point in a 2D plane, you compare distances from the target and keep the smallest ones. The best implementation depends on the size of the input and whether you need a fully sorted answer or just the nearest set.
Start with Squared Distance
You do not need the square root to compare Euclidean distances. Squared distance is enough and avoids extra computation.
That works because the square root function preserves ordering. If point A has a smaller squared distance than point B, it also has a smaller actual distance.
Use a Max-Heap for O(n log k)
When n is large and k is much smaller, a max-heap of size k is a strong general solution. Keep the closest k points seen so far and discard anything farther away.
The heap stores the current best k points, with the farthest of those k at the top. That makes replacement efficient when a closer point appears.
Sort When Simplicity Matters More Than Asymptotic Cost
If the dataset is moderate or you need the results sorted by distance anyway, sorting may be simpler:
This costs O(n log n), which is fine for many real programs and easier to explain in interviews or small utilities.
For very large inputs, a selection algorithm such as quickselect can reduce the average cost toward linear time, but the heap solution is often the best balance of clarity and performance.
If the points are reused for many nearest-neighbor queries rather than one query, a spatial index such as a k-d tree can be a better long-term choice than recomputing distances from scratch every time in production systems at scale globally.
Common Pitfalls
The biggest mistake is computing the full Euclidean distance with square roots when only comparison is needed. That adds work without changing the ranking.
Another common issue is choosing the wrong data structure for the constraints. Sorting everything is simple, but it does more work than necessary when k is tiny compared with n.
People also forget tie behavior. If several points are equally distant from the target, the problem statement may allow any order, but production code should be clear about whether stable ordering matters.
Finally, watch for edge cases:
- '
k = 0' - '
kgreater than the number of points' - duplicate points
- negative coordinates
Those cases are usually easy to support once you decide the desired behavior.
Summary
- Compare squared distances instead of using square roots.
- Use a max-heap of size
kfor an efficientO(n log k)solution. - Use sorting when simplicity is more important than minimizing work.
- Quickselect can be faster on average, but it is more complex to implement correctly.
- Pick the approach that matches the input size and the output-ordering requirement.
Related reading
- Find kth smallest element in a binary search tree in Optimum way
- find kth smallest number in Ologn time
- Find largest rectangle containing only zeros in an N×N binary matrix
- Find length of smallest window that contains all the characters of a string in another string
- Find maximum possible time HHMM by permuting four given digits
- Find minimal Ai2 Bi2 when A and B are sorted
- Find local minima in an array
- Find local minimum in n x n matrix in On time

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.