Skip to main content

Find the Nearest City

medium
Software engineer

You are given a list of $n$ cities with their corresponding $x$ and $y$ coordinates. For a given list of queries (city names), your task is to find the nearest city that shares either the same x-coordinate or the same y-coordinate as the queried city.

Rules

  1. Distance: Use the Manhattan distance to calculate the distance between cities. Since either the x or y coordinate must be the same, the distance will simply be the absolute difference of the non-matching coordinate.
  2. Tie-breaking: If two or more cities have the same minimum distance to the queried city, return the city name that is lexicographically smaller.
  3. Invalid Queries: If a queried city does not exist in the input list, or if no other city shares a coordinate with the queried city, return an empty string "".

Example 1

Input

cities = ["London", "Toronto", "Ajax", "York", "Bayshore", "Paris", "Leduc", "Chicago"], xCoordinates = [0, 1, 2, 4, 5, 0, 1, 0], yCoordinates = [1, 2, 5, 3, 4, 2, 0, 0], queries = ["London", "Toronto", "York", "Albert"]

Output

["Chicago", "Paris", "", ""]

Explanation

- For **London** (0, 1): Shares x=0 with Paris (0, 2) [dist 1] and Chicago (0, 0) [dist 1]. Since distances are tied, 'Chicago' is chosen because it is lexicographically smaller than 'Paris'.
- For **Toronto** (1, 2): Shares x=1 with Leduc (1, 0) [dist 2] and y=2 with Paris (0, 2) [dist 1]. 'Paris' is closer.
- For **York** (4, 3): No other city shares x=4 or y=3. Return "".
- For **Albert**: This city is not in the list. Return "".

Example 2

Input

cities = ["a", "b", "c"], xCoordinates = [1, 1, 1], yCoordinates = [1, 2, 3], queries = ["b"]

Output

["a"]

Explanation

City 'b' at (1, 2) shares x=1 with 'a' (1, 1) and 'c' (1, 3). Both are distance 1 away. 'a' is lexicographically smaller than 'c'.

Example 3

Input

cities = ["p1", "p2"], xCoordinates = [10, 20], yCoordinates = [10, 20], queries = ["p1"]

Output

[""]

Constraints

  • 1 <= n <= 10⁵
  • 1 <= queries.length <= 10⁵
  • 0 <= xCoordinates[i], yCoordinates[i] <= 10⁹
  • City names consist of English letters and are unique.
  • The lengths of cities, xCoordinates, and yCoordinates are equal.

Onsite

ArrayBinary SearchHash TableSortingString
Language
Code editor loads in the browser.

Output

Input

["London","Toronto","Ajax","York","Bayshore","Paris","Leduc","Chicago"]
[0,1,2,4,5,0,1,0]
[1,2,5,3,4,2,0,0]
["London","Toronto","York","Albert"]

Expected

["Chicago","Paris","",""]

Your output

Run to see your output.