K Closest Points to Origin
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Return the k points closest to the origin (0, 0).
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1You do not need the real distance, only an order: x*x + y*y is enough.
- Hint 2Which point on your list of k do you want to be able to remove quickly: the nearest or the farthest?
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
A pizza delivery shop with k riders. You want the k customers nearest to the shop. Keep a list of the k nearest so far, with the farthest of them at the top. A new customer closer than that farthest one replaces him; otherwise ignore the newcomer.
- The obvious way
Sort all points by distance and take the first k: O(n log n).
- The key insight
Keep a max-heap (farthest on top) of at most k points. Push each point with its squared distance; if the heap has more than k, pop the farthest. At the end the heap holds the k closest. O(n log k).
- The algorithm
- For each point compute distance squared = x*x + y*y.
- Push it into a max-heap keyed by that distance.
- If the heap has more than k, pop the farthest.
- Return the points left in the heap.
Watch it run
Examplepoints = [[3,3],[5,-1],[-2,4]], k = 2
Distances squared: (3,3) -> 18, (5,-1) -> 26, (-2,4) -> 20. First two go in: heap holds 18 and 26, farthest 26 on top.
heap: 18, 26
Where people slip
- Skip the square root; comparing squared distances gives the same order.
- The order of the returned points does not matter.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
import heapq
def k_closest(points, k):
heap = [] # max-heap by distance (negatives)
for x, y in points:
distance = x * x + y * y # no square root needed for ordering
heapq.heappush(heap, (-distance, x, y))
if len(heap) > k:
heapq.heappop(heap) # drop the farthest
return [[x, y] for _, x, y in heap]Now close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.