Thursday, March 16, 2006

k closest points to the origin

given n points in 2d space, write an efficient method that will return the k closests points to the origin. Analyze the complexity of the algorithm.

1 comment:

Daniel Winterstein said...

That's got me. I can't see how to improve on the simple thing of scanning through the list keeping a sorted set of the best k. That's O(n log k). Obviously we can drop the relatively expensive square root operation, after which the distance measure is just x*x+y*y which is only 3 operations. You could do a first pass filtering by x+y, then return and consider x^2+y^2, but I doubt you'd gain anything by it.
Monkey stumped. What devious trick is there here?
- Dan