Skip to the code
cf.
+25 XP

#386 Closest Stores to the User

medium

A store locator shows the k stores closest to the user on a map. Store i is at stores[i] = [x, y], and the user is at user = [ux, uy]. Distance is the straight-line distance; comparing squared distances (x - ux)^2 + (y - uy)^2 gives the same order without square roots.

Write closestStores(stores, user, k) that returns the indexes of the k closest stores, closest first. When two stores are equally far, the smaller index comes first. k is between 1 and stores.length.

Example 1

Input: stores = [[1,3],[-2,2],[5,8],[0,1]], user = [0,0], k = 2
Output: [3,1]

Squared distances are 10, 8, 89, 1, so store 3 then store 1.

Example 2

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

All three are 1 away, so the smallest indexes win.

Constraints

  • 1 <= k <= stores.length <= 10^4
  • -10^4 <= x, y, ux, uy <= 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).