Skip to main content
Back to problems
#2359
Medium Algorithms

Find closest node to given two nodes

Depth-First Search Graph Theory
53.0% acceptance
Feb 25, 2026
2096
470
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn closest_meeting_node(edges: Vec<i32>, node1: i32, node2: i32) -> i32 {
    let n = edges.len();
    let bfs = |start: usize| -> Vec<i32> {
      let mut dist = vec![i32::MAX; n];
      dist[start] = 0;
      let mut cur = start as i32;
      while cur != -1 {
        let u = cur as usize;
        let next = edges[u];
        if next == -1 || dist[next as usize] != i32::MAX { break; }
        dist[next as usize] = dist[u] + 1;
        cur = next;
      }
      dist
    };
    let d1 = bfs(node1 as usize);
    let d2 = bfs(node2 as usize);
    let mut best = i32::MAX;
    let mut ans = -1;
    for i in 0..n {
      if d1[i] != i32::MAX && d2[i] != i32::MAX {
        let mx = d1[i].max(d2[i]);
        if mx < best { best = mx; ans = i as i32; }
      }
    }
    ans
  }
}