The problem. Given an array of points, where points[i] = [x, y], and an integer k, return the k points closest to the origin (0, 0), using ordinary straight-line distance √(x² + y²). The answer may be in any order, and it is unique.
points = [[1,3], [-2,2]], k = 1 -> [[-2,2]]
points = [[3,3], [5,-1], [-2,4]], k = 2 -> [[3,3], [-2,4]]
points = [[3,3], [5,-1], [-3,4], [1,1], [-3,-2]], k = 3 -> [[1,1], [-3,-2], [3,3]] (any order)Compare squared distances, x² + y². The square root never changes which point is closer, and skipping it keeps everything in exact integers — no floating-point rounding.
Free account
Sign up to read the rest of this lesson: 6 more sections, 2 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come