The Find Closest Node to Given Two Nodes interview question provides a directed graph where each node has at most one outgoing edge. You are given two starting nodes, node1 and node2. Your goal is to find a node that is reachable from both starting nodes such that the maximum of the distances from node1 to and from node2 to is minimized. If there's a tie, return the node with the smallest index.
Amazon and Google use this problem to test your ability to coordinate multiple traversals. It evaluation your proficiency with Breadth-First Search (BFS) or Depth-First Search (DFS) and your ability to store and compare path information. It’s a great test of "Min-Max" optimization—where you want to find the best among the worst-case scenarios.
This problem uses Multi-source Distance Tracking.
node1 to calculate the distance to all reachable nodes. Store these in an array dist1.node2 to calculate the distance to all reachable nodes. Store these in an array dist2.dist1[i] != -1 and dist2[i] != -1):
max_dist = max(dist1[i], dist2[i]).max_dist and the corresponding node index.Edges: [2, 2, 3, -1] (0->2, 1->2, 2->3, 3 has no edge).
Starting nodes: 0 and 1.
dist1 = [0, -1, 1, 2].dist2 = [-1, 0, 1, 2].max(1, 1) = 1.max(2, 2) = 2.max_dist is 1, found at Node 2.
Result: 2.When a problem asks to minimize the maximum of two distances, always calculate all distances from both sources independently first. This "Precompute and Intersect" strategy is a common Graph interview pattern.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Remove Methods From Project | Medium | Solve | |
| Flower Planting With No Adjacent | Medium | Solve | |
| Keys and Rooms | Medium | Solve | |
| Reorder Routes to Make All Paths Lead to the City Zero | Medium | Solve | |
| Unit Conversion I | Medium | Solve |