Nearest Neighbouring City
Learn this problemProblem statement
A number of cities are placed at distinct integer coordinates on a Cartesian plane. The arrays cities, xCoordinates, and yCoordinates describe each city's name and position.
For every name in queries, find the nearest other city that shares either the same x-coordinate or the same y-coordinate with the queried city. Distance is measured using Manhattan distance: |x1 - x2| + |y1 - y2|.
- If no other city shares an x-coordinate or y-coordinate with the queried city, return
"NONE". - If multiple eligible cities have the same minimum distance, return the lexicographically smallest city name.
Return the answers in the same order as queries.
Function
findNearestCities(numOfCities: int, cities: String[], xCoordinates: int[], yCoordinates: int[], numOfQueries: int, queries: String[]) → String[]Examples
Example 1
numOfCities = 3cities = ["c1", "c2", "c3"]xCoordinates = [3, 2, 1]yCoordinates = [3, 2, 3]numOfQueries = 3queries = ["c1", "c2", "c3"]return = ["c3", "NONE", "c1"]The plot places c1 = (3, 3), c2 = (2, 2), and c3 = (1, 3) at their source coordinates. Cities c1 and c3 share y-coordinate 3, while c2 shares neither coordinate with another city.
Example 2
numOfCities = 3cities = ["fastcity", "bigbanana", "xyz"]xCoordinates = [23, 23, 23]yCoordinates = [1, 10, 20]numOfQueries = 3queries = ["fastcity", "bigbanana", "xyz"]return = ["bigbanana", "fastcity", "bigbanana"]All three cities lie on the vertical line x = 23. Their y-coordinates are 1, 10, and 20, matching the source diagram.
Example 3
numOfCities = 3cities = ["london", "warsaw", "hackerland"]xCoordinates = [1, 10, 20]yCoordinates = [1, 10, 10]numOfQueries = 3queries = ["london", "warsaw", "hackerland"]return = ["NONE", "hackerland", "warsaw"]london = (1, 1) is isolated. warsaw = (10, 10) and hackerland = (20, 10) share y-coordinate 10, so they are nearest to each other.
Example 4
numOfCities = 5cities = ["green", "red", "blue", "yellow", "pink"]xCoordinates = [100, 200, 300, 400, 500]yCoordinates = [100, 200, 300, 400, 500]numOfQueries = 5queries = ["green", "red", "blue", "yellow", "pink"]return = ["NONE", "NONE", "NONE", "NONE", "NONE"]Every city lies on the diagonal x = y, but no two distinct cities share an x-coordinate or a y-coordinate. Therefore every query returns "NONE".
Constraints
More Akuna Capital problems
- Binary CircuitOA · Seen Jul 2026
- Items SortOA · Seen Jul 2026
- Minimize Malware Spread by Removing a NodeOA · Seen Jul 2026
- Maximum K-Star SumOA · Seen Jul 2026
- Profitable Project PairsOA · Seen Jul 2026
- Array Challenge (QR Intern)OA · Seen Jul 2026
- Communications HandlerOA · Seen Jul 2026
- K Smallest SubstringOA · Seen Jul 2026