CodeArchon

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)
0
newest
(-2,2)
1
(5,8)
2
(0,1)
3
MapMax-Heap by d² (size 1)
(1,3)→10
1/7
Narrationstep 1 of 7

Beacon (1,3) squared distance = 10. Push to max-heap.

1import heapq
2def kClosest(points, k):
3 h = []
4 for x, y in points:
5 heapq.heappush(h, (-(x*x+y*y), x, y))
6 if len(h) > k: heapq.heappop(h)
7 return [[x, y] for _, x, y in h]
Variables
x=1
y=3
dist2=10
heapSize=1
k=2

How to think about it

  1. We never need the actual sqrt — squared distance suffices for ordering.
  2. Max-heap at the root reveals the current worst candidate -> cheapest to evict.
  3. 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