Find Closest Node to Given Two Nodes - Problem

You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.

The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from i, then edges[i] == -1.

You are also given two integers node1 and node2.

Return the index of the node that can be reached from both node1 and node2, such that the maximum between the distance from node1 to that node, and from node2 to that node is minimized. If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1.

Note: edges may contain cycles.

Input & Output

Example 1 — Basic Path
$ Input: edges = [2,1,3,-1], node1 = 0, node2 = 3
Output: 2
💡 Note: From node 0: 0→2 (distance 1), from node 3: 3→2 (distance 1). Node 2 can be reached from both with max distance 1.
Example 2 — Linear Chain
$ Input: edges = [1,2,-1], node1 = 0, node2 = 2
Output: 2
💡 Note: From node 0: 0→1→2 (distance 2), from node 2: 2 (distance 0). Node 2 has max distance 2.
Example 3 — No Common Node
$ Input: edges = [1,-1], node1 = 0, node2 = 1
Output: 1
💡 Note: Node 0 can reach nodes {0, 1} with distances {0: 0, 1: 1}. Node 1 can reach {1} with distance {1: 0}. The common reachable node is 1 with max distance max(1, 0) = 1.

Constraints

  • n == edges.length
  • 2 ≤ n ≤ 105
  • -1 ≤ edges[i] < n
  • edges[i] ≠ i
  • 0 ≤ node1, node2 < n

Visualization

Tap to expand
Find Closest Node to Given Two Nodes INPUT Directed Graph Structure 0 2 1 3 2 --> 3 --> 1 (self loop) --> edges array: 2 1 3 -1 [0] [1] [2] [3] node1 = 0 node2 = 3 ALGORITHM STEPS 1 BFS from node1 Calculate dist1[] for all nodes dist1: [0,INF,1,2] 2 BFS from node2 Calculate dist2[] for all nodes dist2: [INF,INF,INF,0] 3 Find max distance For each node: max(d1, d2) Node 0: max(0, INF) = INF Node 1: max(INF, INF) = INF Node 2: max(1, INF) = INF Node 3: max(2, 0) = 2 4 Find minimum Return node with min max-dist Note: Only node 3 reachable from both paths. Min = node 3 (dist=2) FINAL RESULT Closest Node Found 0 2 1 3 d=1 d=1 node1 node2 Output: 3 max distance = 2 Node 3 is reachable from node1 (dist 2) and node2 (dist 0) Key Insight: Two-Pass BFS calculates distances from both start nodes independently. For each candidate node, we compute max(dist1[i], dist2[i]) and find the node minimizing this value. This ensures the closest meeting point where the longer path is as short as possible. Time: O(n), Space: O(n). TutorialsPoint - Find Closest Node to Given Two Nodes | Two-Pass Distance Calculation Approach
Asked in
Google 12 Amazon 8 Microsoft 6
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen