Find the nearest city sharing axis
Company: DoorDash
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithmic problem-solving and data-structuring skills for efficient spatial queries constrained to shared axes, including handling tie-breaking rules and preprocessing for fast lookups.
Constraints
- 1 <= N <= 10^5 cities.
- City names are unique, non-empty strings.
- Coordinates x, y are integers and may be negative.
- The query city is one of the given cities (or may be absent, in which case return None).
- A city only counts as a candidate if it shares the same x OR the same y as the query.
Examples
Input: ([['A', 0, 0], ['B', 0, 3], ['C', 0, 5], ['D', 7, 0]], 'A')
Expected Output: 'B'
Explanation: B, C share x=0 (dist 3, 5); D shares y=0 (dist 7). Nearest is B at distance 3.
Input: ([['A', 0, 0], ['B', 0, 2], ['C', 2, 0]], 'A')
Expected Output: 'B'
Explanation: B shares x (dist 2), C shares y (dist 2) -> tie; lexicographically smaller name 'B' wins.
Input: ([['A', 1, 1], ['B', 1, 4], ['C', 5, 1]], 'A')
Expected Output: 'B'
Explanation: B shares x=1 (dist 3); C shares y=1 (dist 4). B is closer.
Input: ([['Z', 0, 0], ['Y', 0, 2], ['X', 2, 0]], 'Z')
Expected Output: 'X'
Explanation: Y shares x (dist 2) and X shares y (dist 2) -> tie; 'X' < 'Y' lexicographically.
Input: ([['A', 0, 0], ['B', 5, 5]], 'A')
Expected Output: None
Explanation: B shares neither x nor y with A, so there is no valid neighbor.
Input: ([['Solo', 3, 3]], 'Solo')
Expected Output: None
Explanation: The query is the only city; itself is excluded, so no answer exists.
Input: ([['A', 0, 0], ['B', 0, -4], ['C', -4, 0]], 'A')
Expected Output: 'B'
Explanation: B shares x (dist 4) and C shares y (dist 4) -> tie with negatives; 'B' < 'C' wins.
Input: ([['A', 2, 2], ['B', 2, 7], ['C', 9, 2], ['D', 2, -3]], 'A')
Expected Output: 'B'
Explanation: B shares x (dist 5), D shares x (dist 5), C shares y (dist 7). Tie between B and D at dist 5; 'B' < 'D'.
Hints
- A city is a candidate only if it shares the query's x or the query's y. The distance you compare is along the OTHER axis: if x matches, compare |y - qy|; if y matches, compare |x - qx|.
- Track the best (smallest) distance seen so far. On a distance tie, prefer the lexicographically smaller name.
- For efficiency at scale, group cities by x and by y (or sort and binary-search). Within the query's x-group the nearest neighbor by y is one of the two adjacent entries; same idea for the y-group.