You are given a list of points on a flat plane, points, where each point is [x, y], and a number k. Distance is the usual straight-line distance, √(x² + y²) from the origin (0, 0).
Return the k points nearest the origin, in any order. The test data makes sure there is no tie at the cut-off, so exactly one set of k points is right.
Example 1
Input: points = [[3, 1], [-1, 2], [2, -3], [0, 1]], k = 2 Output: [[-1, 2], [0, 1]] Why: squared distances are 10, 5, 13 and 1; the two smallest are 1 and 5
2 more examples and the constraints
Example 2
Input: points = [[5, 5], [-2, 1]], k = 1 Output: [[-2, 1]] Why: 4 + 1 = 5 beats 25 + 25 = 50
Example 3
Input: points = [[1, 1], [2, 2], [-3, 0]], k = 3 Output: [[1, 1], [2, 2], [-3, 0]] Why: k is every point, so all of them come back
Constraints
- 1 ≤ k ≤ number of points ≤ 10,000
- Every x and y is between −10,000 and 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort by distanceO(n log n)
- Max-heap of size kO(n log k)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 points, k = 10 | Verdict |
|---|---|---|---|
| Sort by distance | O(n log n) | Passes; simplest to write | |
| Max-heap of size k | O(n log k) | Best; streams the points |
n = number of points, k = how many to return.
Edge cases to test
- k equals the number of points. Every point is returned; nothing is ever popped.
- Ties below the cut-off. (1, 0) and (0, 1) are equally close; with k = 2 both are kept.
- The origin itself. (0, 0) has distance 0 and is always among the closest.
- Coordinates at the limits. 10,000² + 10,000² = 200,000,000 still fits in a 32-bit int.
- Repeated points. Two copies of (2, 2) are two separate points and can both be returned.
Common mistakes
- Taking the square root, which is slower and brings in floating-point error for no gain.
- Using a min-heap of size k, which pops the closest point instead of the farthest.
- Popping before pushing, which throws out a kept point even when the new one is farther away.
How to talk through it
- 1Clarify. Any order for the result? Can there be ties at the cut-off? How large is k compared with n?
- 2Give the sort. Sort by x² + y² and take k: O(n log n). Say why the square root is not needed.
- 3Point out the waste. You only need the k smallest, not the full order. A heap of size k does that.
- 4Code the heap. Push, and pop the top when the size passes k. Explain why it is a max-heap.
- 5Test out loud. Run k equal to n and a tie that sits inside the first k before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?