Skip to main content
Back to LeetCode Archive
May 30, 20255 min read

2359. Find Closest Node to Given Two Nodes (30 May 2025)

DFSGraph

You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most oneoutgoing 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.


🧪 Examples

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.

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.length
  • 2 <= n <= 10^5
  • -1 <= edges[i] < n
  • edges[i] != i
  • 0 <= node1, node2 < n

🧠 Intuition

  • Idea is to use DFS to find the distance from the source nodes to all target node
  • We do a DFS from node1 and node2 => total of O(n)O(n) operations
  • Then we also loop through the distance array returned again O(n)O(n)

💡 Approach

  • Let's do a DFS to find the distance from node1 and node2 to all other nodes
    • Algorithm can be designed by taking the property that each node will have at-most one outgoing edge.
  • Our DFS function returns arrays of distances, a[0..n−1]a[0..n-1] and b[0..n−1]b[0..n-1].
  • Then we loop from 0..n−10..n-1 and check:
    • If result<max⁡(a[i],b[i])\text{result} < \max(a[i], b[i]):
      • Update result=max⁡(a[i],b[i])\text{result} = \max(a[i], b[i])
  • Finally we return the result.

✅ Final Code (Language: C++)

class Solution {
 
public:
 
    vector<int> computeDistDFS(vector<int>& edges, int startNode) {
 
        int n = edges.size();
 
        vector<int> result(n, -1);
 
        int dist = 0;
 
        vector<bool> visited(n,false);
 
        do {
 
            visited[startNode] = true;
 
            result[startNode] = dist;
 
            dist++;
 
            startNode = edges[startNode];
 
        } while (startNode != -1 && !visited[startNode]);
 
        return result;
 
    }
 
    int closestMeetingNode(vector<int>& edges, int node1, int node2) {
 
        vector<int> result1, result2;
 
        int n = edges.size();
 
        result1 = computeDistDFS(edges, node1);
 
        result2 = computeDistDFS(edges, node2);
 
        int resultNode = -1;
 
        int result = INT_MAX;
 
        for (int i = 0; i < n; i++) {
 
            if (result1[i] == -1 || result2[i] == -1)
 
                continue;
 
            int temp = max(result1[i], result2[i]);
 
            if (temp < result) {
 
                result = temp;
 
                resultNode = i;
 
            }
 
        }
 
        return resultNode;
 
    }
 
};

📊 Complexity

  • Time Complexity:
    • We do only order of nn operation on the array multiple times. Two DFS for each node and one final loop to go through the results. So final complexity is O(n)O(n)
  • Space Complexity:
    • We have extra storage for visited, result1 and result2 in O(n)O(n) => final space complexity is O(n)O(n)