Skip to the code
cf.
+25 XP

#216 Closest Stores to the Warehouse

medium

A delivery map shows the k stores closest to the warehouse, which sits at [0, 0]. stores holds each store's position as [x, y]. Distance is the usual straight-line distance.

Write closestStores(stores, k) that returns the k closest positions, in any order. The tests guarantee the answer is unique (no tie at the cutoff).

Example 1

Input: stores = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]

[-2, 2] is about 2.83 away; [1, 3] is about 3.16 away.

Example 2

Input: stores = [[3,3],[5,-1],[-2,4]], k = 2
Output: [[3,3],[-2,4]]

Squared distances are 18, 26, and 20. The two smallest are 18 and 20.

Constraints

  • 1 <= k <= stores.length <= 10000
  • -10^4 <= x, y <= 10^4
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).