mediumHeap / Priority QueueFacebookAmazonUberGoogle
Nearest Beacon Filter
A space station retains telemetry links for only the K nearest beacons, dropping farther ones as new signals arrive.
Given an array of 2-D points and integer k, return the k points closest to the origin by Euclidean distance.
Choose approach
(1,3)
0newest
(-2,2)
1(5,8)
2(0,1)
3MapMax-Heap by d² (size 1)
(1,3)→10
1/7
Narrationstep 1 of 7
Beacon (1,3) squared distance = 10. Push to max-heap.
Variables
x=1
y=3
dist2=10
heapSize=1
k=2
How to think about it
- We never need the actual sqrt — squared distance suffices for ordering.
- Max-heap at the root reveals the current worst candidate -> cheapest to evict.
- Stream-friendly; O(1) extra per point.
Edge cases to catch in interview
- k == n -> return everything.
- Points equidistant -> ties broken arbitrarily.
Examples
Example 1
[[-2,2]]{"points":[[1,3],[-2,2]],"k":1,"values":["(1,3)","(-2,2)"]}
Example 2
[[3,3],[-2,4]]{"points":[[3,3],[5,-1],[-2,4]],"k":2,"values":["(3,3)","(5,-1)","(-2,4)"]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed