Find Closest Node to Given Two Nodes
MedPrompt
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 that edges may contain cycles.
Example 1:
Input: edges = [2,2,3,-1], node1 = 0, node2 = 1
Output: 2
Explanation: The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1.
The maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2.Example 2:
Input: edges = [1,2,-1], node1 = 0, node2 = 2
Output: 2
Explanation: The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0.
The maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2.
Constraints:
n == edges.length2 <= n <= 105-1 <= edges[i] < nedges[i] != i0 <= node1, node2 < n
Approaches
2 approaches with complexity analysis and trade-offs.
This approach iterates through every node in the graph, treating each one as a potential meeting point. For each potential meeting node, it calculates the distance from node1 and node2 by performing separate traversals from each starting node. It then keeps track of the node that minimizes the maximum of these two distances.
Algorithm
- Initialize
min_max_disttoInteger.MAX_VALUEandresult_nodeto -1. - Loop through each node
ifrom0ton-1to consider it as a potential meeting node. - Inside the loop, define a helper function
getDistance(start, end, edges)to calculate the distance from astartnode to anendnode. - This helper function traverses from
start, incrementing a distance counter. It uses avisitedarray to detect and handle cycles, preventing infinite loops. - If
endis reached, it returns the distance; otherwise, it returns -1. - Call
getDistanceto find the distanced1fromnode1toi. - If
iis reachable fromnode1(d1 != -1), callgetDistanceagain to find the distanced2fromnode2toi. - If
iis reachable from both (d2 != -1), calculatemaxDist = Math.max(d1, d2). - If
maxDistis less thanmin_max_dist, updatemin_max_disttomaxDistandresult_nodetoi. - After checking all nodes, return
result_node.
Walkthrough
The core idea is to test all possibilities. We can write a helper function, getDistance(start, end, edges), that finds the shortest path distance from a start node to an end node. This function would traverse the graph from start, keeping track of the distance, until it either reaches end, a dead end (-1), or a cycle. To handle cycles, a visited array is necessary within this helper function.
The main function then iterates through all nodes i from 0 to n-1. For each i, it calls getDistance(node1, i, ...) and getDistance(node2, i, ...). If node i is reachable from both, it computes the maximum of the two distances. This maximum distance is compared with the minimum one found so far. If the current node i offers a strictly smaller maximum distance, it becomes the new best candidate. If the distances are equal, the node with the smaller index is preferred, which is naturally handled by iterating i in increasing order.
class Solution { public int closestMeetingNode(int[] edges, int node1, int node2) { int n = edges.length; int minMaxDist = Integer.MAX_VALUE; int resultNode = -1; for (int i = 0; i < n; i++) { int d1 = getDistance(node1, i, edges); if (d1 != -1) { int d2 = getDistance(node2, i, edges); if (d2 != -1) { int maxDist = Math.max(d1, d2); if (maxDist < minMaxDist) { minMaxDist = maxDist; resultNode = i; } } } } return resultNode; } private int getDistance(int startNode, int endNode, int[] edges) { int dist = 0; int currNode = startNode; boolean[] visited = new boolean[edges.length]; while (currNode != -1 && !visited[currNode]) { if (currNode == endNode) { return dist; } visited[currNode] = true; currNode = edges[currNode]; dist++; } return -1; }}Complexity
Time
O(n^2) - The main loop runs `n` times. Inside the loop, the `getDistance` helper function can traverse up to `n` nodes in the worst case. This results in a quadratic time complexity.
Space
O(n) - The `getDistance` function uses a `visited` boolean array of size `n` to handle cycles. This array is re-created for each call within the main loop.
Trade-offs
Pros
Conceptually straightforward and easy to understand.
Cons
Highly inefficient due to redundant computations for each potential meeting node.
Very likely to result in a 'Time Limit Exceeded' error on platforms like LeetCode for the given constraints.
Solutions
Solution
public class Solution { public int ClosestMeetingNode(int[] edges, int node1, int node2) { int n = edges.Length; List < int > [] g = new List < int > [n]; for (int i = 0; i < n; ++i) { g[i] = new List < int > (); if (edges[i] != -1) { g[i].Add(edges[i]); } } int inf = 1 << 30; int[] f(int i) { int[] dist = new int[n]; Array.Fill(dist, inf); dist[i] = 0; Queue < int > q = new Queue < int > (); q.Enqueue(i); while (q.Count > 0) { i = q.Dequeue(); foreach(int j in g[i]) { if (dist[j] == inf) { dist[j] = dist[i] + 1; q.Enqueue(j); } } } return dist; } int[] d1 = f(node1); int[] d2 = f(node2); int ans = -1, d = inf; for (int i = 0; i < n; ++i) { int t = Math.Max(d1[i], d2[i]); if (t < d) { d = t; ans = i; } } return ans; }}Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.