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.
A much more efficient approach is to pre-calculate the distances from node1 and node2 to all other nodes in the graph. We can do this in just two separate traversals. Once we have these distances, we can iterate through all the nodes once to find the one that satisfies the condition.
Algorithm
- Create a helper function
calculateDistances(startNode, edges, dist)that populates a given distance array. - Inside the helper, start a traversal from
startNode. Since each node has at most one outgoing edge, this is a simple walk. - Keep track of the current distance
d. As you visit eachcurrNode, setdist[currNode] = dand move to the next nodeedges[currNode]. - Stop the traversal if you reach a dead end (
-1) or a node that has already been visited (to handle cycles). - Create two distance arrays,
dist1anddist2, of sizen, initialized with -1. - Call
calculateDistances(node1, edges, dist1)to filldist1with distances fromnode1. - Call
calculateDistances(node2, edges, dist2)to filldist2with distances fromnode2. - Initialize
min_max_dist = Integer.MAX_VALUEandresult_node = -1. - Iterate through all nodes
ifrom0ton-1. - If
dist1[i]anddist2[i]are not -1 (meaningiis reachable from both), calculatemaxDist = Math.max(dist1[i], dist2[i]). - If
maxDist < min_max_dist, updatemin_max_dist = maxDistandresult_node = i. - Return
result_node.
Walkthrough
This method avoids the O(n^2) complexity by computing all required distances upfront.
- First, we create a distance array,
dist1, and populate it by traversing the graph starting fromnode1. Since each node has at most one outgoing edge, this traversal is a simple walk along a path. We store the distance fromnode1to every reachable nodeiindist1[i]. The traversal automatically stops at dead ends or already visited nodes, correctly handling paths and cycles. - Second, we do the same for
node2, creating and populating adist2array. - Finally, we iterate through all nodes
ifrom0ton-1. For each node, we check if it's reachable from both starting nodes (by checking ifdist1[i]anddist2[i]are not -1). If so, we calculatemax(dist1[i], dist2[i])and compare it with the minimum maximum distance found so far. We update our answer if we find a better meeting node. Because we iterate through the nodes in increasing order of their indices, the first node we find for a given minimum distance will automatically be the one with the smallest index, satisfying the tie-breaking rule.
class Solution { public int closestMeetingNode(int[] edges, int node1, int node2) { int n = edges.length; int[] dist1 = new int[n]; int[] dist2 = new int[n]; Arrays.fill(dist1, -1); Arrays.fill(dist2, -1); // Calculate distances from node1 calculateDistances(node1, edges, dist1); // Calculate distances from node2 calculateDistances(node2, edges, dist2); int minMaxDist = Integer.MAX_VALUE; int resultNode = -1; for (int i = 0; i < n; i++) { if (dist1[i] != -1 && dist2[i] != -1) { int maxDist = Math.max(dist1[i], dist2[i]); if (maxDist < minMaxDist) { minMaxDist = maxDist; resultNode = i; } } } return resultNode; } private void calculateDistances(int startNode, int[] edges, int[] dist) { int currNode = startNode; int d = 0; while (currNode != -1 && dist[currNode] == -1) { dist[currNode] = d++; currNode = edges[currNode]; } }}Complexity
Time
O(n) - We perform two traversals, each taking at most O(n) time. The final loop to find the result node also takes O(n) time. Thus, the total time complexity is linear with respect to the number of nodes.
Space
O(n) - We use two arrays, `dist1` and `dist2`, each of size `n`, to store the distances from the starting nodes. This results in linear space complexity.
Trade-offs
Pros
Optimal time complexity, making it efficient for large graphs.
The logic is clean and directly solves the problem without redundant work.
Cons
Requires O(n) extra space for the distance arrays, which might be a concern for extremely memory-constrained environments.
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; }}class Solution {private int n;private List<Integer>[] g;public int closestMeetingNode(int[] edges, int node1, int node2) { n = edges.length; g = new List[n]; Arrays.setAll(g, k->new ArrayList<>()); for (int i = 0; i < n; ++i) { if (edges[i] != -1) { g[i].add(edges[i]); } } int[] d1 = dijkstra(node1); int[] d2 = dijkstra(node2); int d = 1 << 30; int ans = -1; for (int i = 0; i < n; ++i) { int t = Math.max(d1[i], d2[i]); if (t < d) { d = t; ans = i; } } return ans; }private int[] dijkstra(int i) { int[] dist = new int[n]; Arrays.fill(dist, 1 << 30); dist[i] = 0; PriorityQueue<int[]> q = new PriorityQueue<>((a, b)->a[0] - b[0]); q.offer(new int[]{0, i}); while (!q.isEmpty()) { var p = q.poll(); i = p[1]; for (int j : g[i]) { if (dist[j] > dist[i] + 1) { dist[j] = dist[i] + 1; q.offer(new int[]{dist[j], j}); } } } return dist; }}class Solution {public: int closestMeetingNode(vector<int> &edges, int node1, int node2) { int n = edges.size(); vector<vector<int>> g(n); for (int i = 0; i < n; ++i) { if (edges[i] != -1) { g[i].push_back(edges[i]); } } const int inf = 1 << 30; using pii = pair<int, int>; auto dijkstra = [&](int i) { vector<int> dist(n, inf); dist[i] = 0; priority_queue<pii, vector<pii>, greater<pii>> q; q.emplace(0, i); while (!q.empty()) { auto p = q.top(); q.pop(); i = p.second; for (int j : g[i]) { if (dist[j] > dist[i] + 1) { dist[j] = dist[i] + 1; q.emplace(dist[j], j); } } } return dist; }; vector<int> d1 = dijkstra(node1); vector<int> d2 = dijkstra(node2); int ans = -1, d = inf; for (int i = 0; i < n; ++i) { int t = max(d1[i], d2[i]); if (t < d) { d = t; ans = i; } } return ans; }};class Solution: def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: def dijkstra(i): dist = [inf] * n dist[i] = 0 q = [(0, i)] while q: i = heappop(q)[1] for j in g[i]: if dist[j] > dist[i] + 1: dist[j] = dist[i] + 1 heappush(q, (dist[j], j)) return dist g = defaultdict(list) for i, j in enumerate(edges): if j != - 1: g[i]. append(j) n = len(edges) d1 = dijkstra(node1) d2 = dijkstra(node2) ans, d = - 1, inf for i, (a, b) in enumerate(zip(d1, d2)): if (t: = max(a, b)) < d: d = t ans = i return ansVideo 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.