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 only reach node 1, but node 1 cannot reach any other nodes. No common reachable node exists.

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: Minimize Maximum Distance0123Start 1Start 2Meeting PointDistance from node 0 to node 2: 1 step (0→1→2)Distance from node 3 to node 2: 1 step (3→2)Optimal: Node 2 with max distance = max(1,1) = 1
Understanding the Visualization
1
Input Graph
Directed graph with edges=[2,1,3,-1], node1=0, node2=3
2
Calculate Distances
Find distances from both starting nodes to all reachable nodes
3
Find Minimum
Return node with minimum maximum distance
Key Takeaway
🎯 Key Insight: Calculate distances from both starting nodes, then find the node that minimizes the maximum distance between them
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