Find Closest Node to Given Two Nodes - Problem

Imagine you're navigating through a unique road network where each intersection has at most one outgoing road. This creates an interesting graph structure that might contain cycles or dead ends!

You're given a directed graph of n nodes numbered from 0 to n-1. The graph is represented by an array edges where edges[i] tells you which node you can reach from node i. If there's no outgoing edge from node i, then edges[i] = -1.

Your mission: Find a meeting point that both node1 and node2 can reach, such that the maximum distance either traveler needs to walk is minimized. If multiple meeting points exist with the same optimal distance, choose the one with the smallest index.

Key Challenge: The graph may contain cycles, so you need to handle infinite loops carefully!

Input & Output

example_1.py โ€” Basic Path
$ Input: edges = [2,2,3,-1], node1 = 0, node2 = 1
โ€บ Output: 2
๐Ÿ’ก Note: Node 0 can reach node 2 in 1 step (0โ†’2). Node 1 can reach node 2 in 1 step (1โ†’2). The maximum distance is max(1,1) = 1, making node 2 the optimal meeting point.
example_2.py โ€” Cycle Handling
$ Input: edges = [1,2,0,-1], node1 = 0, node2 = 2
โ€บ Output: 1
๐Ÿ’ก Note: There's a cycle 0โ†’1โ†’2โ†’0. From node 0: reaches node 1 in 1 step, node 2 in 2 steps. From node 2: reaches node 0 in 1 step, node 1 in 2 steps. Node 1 gives max(1,2) = 2, node 0 gives max(2,1) = 2. Node 1 has smaller index, so answer is 1.
example_3.py โ€” No Common Node
$ Input: edges = [1,-1], node1 = 0, node2 = 1
โ€บ Output: -1
๐Ÿ’ก Note: Node 0 can reach node 1, but node 1 has no outgoing edge and cannot reach node 0. There's no node that both can reach, so return -1.

Constraints

  • n == edges.length
  • 2 โ‰ค n โ‰ค 105
  • edges[i] == -1 or 0 โ‰ค edges[i] < n
  • edges[i] != i (no self-loops in input)
  • 0 โ‰ค node1, node2 < n

Visualization

Tap to expand
ABCDEStart 1Start 2Optimal Meeting PointDistance AnalysisFrom A to B: 1 stepFrom D to B: 1 stepMax distance: 1Alternative: Node CFrom A: 2 stepsFrom D: 2 stepsMax distance: 2๐ŸŽฏ Choose node B: minimizes max(1,1) = 1
Understanding the Visualization
1
Map the Network
Each node has at most one outgoing edge, creating chains and cycles
2
Calculate Distances
Use BFS from both starting points to find distances to all reachable nodes
3
Find Common Nodes
Identify nodes that both travelers can reach
4
Minimize Maximum
Choose the meeting point that minimizes the longer of the two journeys
Key Takeaway
๐ŸŽฏ Key Insight: Use BFS to efficiently compute distances while handling cycles, then minimize the maximum distance to ensure fair meeting point for both travelers.
Asked in
Google 45 Amazon 38 Microsoft 25 Meta 20
35.0K Views
Medium-High Frequency
~25 min Avg. Time
1.5K 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