Leetcode 2359: Find Closest Node to Given Two Nodes

grid47
grid47
Exploring patterns and algorithms
Mar 16, 2024 6 min read

You are given a directed graph with n nodes, where each node can have at most one outgoing edge. You are provided with an array edges representing the graph, where edges[i] indicates a directed edge from node i to node edges[i] (or -1 if there is no outgoing edge). You are also given two nodes node1 and node2. The task is to return the node that is reachable from both node1 and node2, such that the maximum of the distances from node1 and node2 to that node is minimized. If there are multiple such nodes, return the smallest index, or return -1 if no such node exists.
Problem
Approach
Steps
Complexity
Input: The input consists of the following elements: an array `edges` of size n (1 <= n <= 10^5) representing the graph, and two integers `node1` and `node2` (0 <= node1, node2 < n).
Example: edges = [1, 2, -1], node1 = 0, node2 = 2
Constraints:
• 2 <= n <= 10^5
• -1 <= edges[i] < n
• edges[i] != i
• 0 <= node1, node2 < n
Output: Return the index of the node that can be reached from both `node1` and `node2` with the minimized maximum distance, or -1 if no such node exists.
Example: Output: 2
Constraints:
• Return the node index with the smallest maximum distance.
Goal: The goal is to find the node that minimizes the maximum distance from both `node1` and `node2` to that node.
Steps:
• Perform Depth-First Search (DFS) to calculate the distance from `node1` and `node2` to all other nodes.
• Iterate through all nodes, calculate the maximum distance for each node, and track the smallest such maximum.
Goal: The graph can contain cycles and may have up to 10^5 nodes. Ensure that your solution handles large inputs efficiently.
Steps:
• The graph may contain cycles.
• Nodes are indexed from 0 to n-1.
Assumptions:
• The graph may contain cycles, but each node has at most one outgoing edge.
• There is no self-loop (edges[i] != i).
Input: edges = [2, 2, 3, -1], node1 = 0, node2 = 1
Explanation: The possible distances to nodes from `node1` and `node2` are compared. The maximum of the distances to each node is calculated, and node 2 minimizes this value.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus