intermediate7 min read·Updated October 1, 2026
K Closest Points to Origin Explained: [[1,3],[-2,2],[2,-2]] Walkthrough
Master the K Closest Points to Origin algorithm. Walk through [[1,3],[-2,2],[2,-2]] with mental models, max-heaps, and edge cases.
By Learnisim AI·Published October 1, 2026
LEARNING ARCSetup → Model in the example → Full trace → Twist → Edge cases → Apply
PREREQUISITES
- Basic arrays and coordinates
- Euclidean distance formula
- Introduction to heaps or priority queues
Why
Why We Need Smart Sorting for K Closest Points to Origin
Phase 1: The Multi-Dimensional Sorting Dilemma
Imagine you are building a ride-sharing dispatch system. You have thousands of driver coordinates flooding in every second, and a passenger at the origin needs the nearest drivers. You are handed a concrete coordinate set:
points = [[1,3],[-2,2],[2,-2]] and you need to find the two closest to the origin. If you blindly calculate and sort every distance from scratch every time a request arrives, your system will choke as the scale of points grows from three to three million.Calculating raw distances for all points requires floating-point square roots, and sorting the entire dataset just to grab a small slice of size wastes massive CPU cycles. We need a way to filter or prioritize distances on the fly without paying the penalty of fully sorting every single coordinate in the space. Understanding how to solve this for our small coordinate set unlocks the exact same mechanism used by massive spatial databases.
Model
The Geometric Model for Finding K Closest Points to Origin
Phase 2: Mapping Points to Radial Distance
When working with spatial coordinate geometry, finding the nearest items to a fixed reference frame like requires a reliable measure of separation. For our locked working example of points = and , we do not need the full square root of the Euclidean distance formula to judge proximity. Because the square root function is strictly monotonic for non-negative numbers, comparing the squared distance preserves the exact same ordering while avoiding costly floating-point square root operations.
Let us map each coordinate pair from our working example to its squared distance metric from the origin:
- Point computes to .
- Point computes to .
- Point computes to .
- Point computes to .
- Point computes to .
Our mental model treats the Euclidean plane as a set of concentric circles radiating outward from the origin . Finding the closest points is equivalent to expanding a circular boundary around the origin until it captures exactly points. In this geometric landscape, both and sit on a circle of radius , whereas sits further out on a circle of radius .
Worked example
Tracing the Algorithm for K Closest Points to Origin
Phase 3: Walking Through the Distance Calculations
Let us apply our squared Euclidean distance model to the locked example where and . Following our geometric blueprint, we bypass square roots to keep our operations strictly within clean integer arithmetic. We calculate the squared distance for every single coordinate pair in our input list.
Given
Steps
1. Compute squared distance for :
2. Compute squared distance for :
3. Compute squared distance for :
4. Rank and select items:
Our calculated distances are 10, 8, and 8. Sorting these in ascending order gives us squared distances of 8, 8, and 10. Because we want the smallest entries, we pick the two coordinates tied for a distance of 8.
Our calculated distances are 10, 8, and 8. Sorting these in ascending order gives us squared distances of 8, 8, and 10. Because we want the smallest entries, we pick the two coordinates tied for a distance of 8.
Result
The coordinate with a squared distance of 10 is successfully filtered out.
Try this: Given points = [[1, 3], [-2, 2], [2, -2]] and k = 2, explain what changes in the final selection if k is reduced from 2 to 1.
Practice
Practice Finding the K Closest Points to Origin
Phase 4: Practice
Now it is your turn to apply the squared distance and selection logic we walked through. In our previous step, we evaluated
[[1,3], [-2,2], [2,-2]] for and found that the points [-2,2] and [2,-2] (both with distance squared equal to 8) were closer than [1,3] (distance squared equal to 10).Consider a slightly modified scenario using the same foundational principles. Suppose your input points are
[[1,1], [3,4], [-1,1]] and you need to find the closest points to the origin . Compute the squared Euclidean distances for each coordinate, rank them, and determine which two points belong in your final result set.Apply
Transferring Spatial Distance Logic to Real-World Search
Phase 5: Adapting the Pattern Beyond Static Lists
We started our journey with points = and , discovering that squared Euclidean distances let us isolate the two closest coordinates to the origin without computing square roots. But what happens when our coordinate stream grows dynamically, or when our distance metric shifts from physical space to multi-dimensional feature embeddings in a recommendation system?
When scaling this pattern to streaming or high-dimensional applications, the core principle remains identical: maintain a bounded set of size using a max-heap (or partition buffer) so you never pay the full sorting tax for all incoming records. If your coordinates represent customer delivery locations or product vectors, the distance formula might change from to a dot product or cosine similarity, but the structural flow of filtering, bounding, and selecting top- elements transfers directly.
Transfer Challenge
Imagine you are building a rideshare matching service where coordinates arrive as a continuous stream, and you must constantly report the closest drivers to a new passenger at the origin . Instead of sorting all historical driver coordinates every time a new driver logs in, how should you adapt the max-heap logic we used for our sample set to handle incoming updates efficiently?
FAQ
Why do we use a max-heap instead of a min-heap for K closest points?
A max-heap of size K lets us keep track of the K smallest distances seen so far by evicting the single largest distance whenever our collection exceeds size K.
How does the algorithm handle the [[1,3],[-2,2],[2,-2]] example with K=2?
We compute squared distances: [1,3] is 10, [-2,2] is 8, and [2,-2] is 8. A max-heap keeps the two smallest (8 and 8), correctly evicting 10 to leave [-2,2] and [2,-2].
Do we need to take the square root when calculating Euclidean distance?
No. Comparing squared distances (x² + y²) avoids floating-point inaccuracies and is faster to compute since relative ordering remains identical.
What is the time complexity of the heap approach for this problem?
O(N log K) time, where N is the total number of points and K is the number of closest points requested, with O(K) space complexity for the heap.