NewProject Coding is here — build features and fix bugs in real codebases with an AI assistantSee what's new

(This question is a variation of the LeetCode question 1779. Find Nearest Point That Has the Same X or Y Coordinate . If you haven't completed that question yet, it is recommended to solve it first.)

Given a list of cities with their (x, y) coordinates. For each queried city, find the nearest city that shares the same x or y coordinate. The distance between two cities is calculated using Manhattan distance. If there are multiple possible answers with the same distance, return the one that is lexicographically smallest. If such a city does not exist, return an empty string.

Note that the Manhattan distance between two coordinates (x1,y1)(x_1, y_1) and (x2,y2)(x_2, y_2) is calculated as ∣x1−x2∣+∣y1−y2∣|x_1 - x_2| + |y_1 - y_2|.

Implement the CityMap class:

  • CityMap(String[] cities, int[] xCoordinates, int[] yCoordinates) Initialize the cities with names, x coordinates and y coordinates.
  • String getNearestCity(String query) Return the name of the nearest city for the queried city name.

Constraints:

  • The number of cities will be in the range [1, 10510^5].
  • All city names are unique and consist of uppercase and lowercase English letters.
  • Coordinates are integers within the range [−106-10^6, 10610^6].

Example 1:

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"] ]
Output: [null, "Chicago", "Paris", "", ""]
Explanation:

  • CityMap cityMap = new CityMap(cities, xCoordinates, yCoordinates)
  • getNearestCity("London") // Return "Chicago". Cities sharing x = 0 or y = 1 are "Paris", and "Chicago", both at a distance of 1. "Chicago" is lexicographically smaller than "Paris".
  • getNearestCity("Toronto") // Returns "Paris". Cities sharing x = 1 or y = 2 are "Leduc", and "Paris". Paris is the closest with a distance of 1.
  • getNearestCity("York") // Return "". No other city shares x = 4 or y = 3
  • getNearestCity("Albert") //Return "", because "Albert" is not in the list.

Accepted
1.1k/2.9k
Acceptance Rate37.4%
Test Cases
Input
Output
Expected