Tap here to switch tabs
Problem
Submissions

Problem: Find Closest Node to Given Two Nodes

Try to solve the Find Closest Node to Given Two Nodes problem.

Statement

You are given a directed graph of n nodes labeled from 00 to n −1- 1, where each node has at most one outgoing edge.

The graph is represented by an array edges of length n, where edges[i] denotes a directed edge from node i to node edges[i]. If node i has no outgoing edge, then edges[i] == −1-1.

You are also given two node identifiers, node1 and node2.

Find the node that is reachable from both node1 and node2 such that the maximum of the distance from node1 to this node and the distance from node2 to this node is minimized. If multiple nodes satisfy this condition, return the one with the smallest index. If no common node is reachable from both node1 and node2, return −1-1.

Constraints:

  • n ==== edges.length

  • 2≤2 \leq n ≤105\leq 10^5

  • −1≤-1 \leq edges[i] <n< n

  • edges[i] ≠\neq i

  • 0≤0 \leq node1, node2 <n< n

⋮
Tap here to switch tabs
Problem
Submissions

Problem: Find Closest Node to Given Two Nodes

Try to solve the Find Closest Node to Given Two Nodes problem.

Statement

You are given a directed graph of n nodes labeled from 00 to n −1- 1, where each node has at most one outgoing edge.

The graph is represented by an array edges of length n, where edges[i] denotes a directed edge from node i to node edges[i]. If node i has no outgoing edge, then edges[i] == −1-1.

You are also given two node identifiers, node1 and node2.

Find the node that is reachable from both node1 and node2 such that the maximum of the distance from node1 to this node and the distance from node2 to this node is minimized. If multiple nodes satisfy this condition, return the one with the smallest index. If no common node is reachable from both node1 and node2, return −1-1.

Constraints:

  • n ==== edges.length

  • 2≤2 \leq n ≤105\leq 10^5

  • −1≤-1 \leq edges[i] <n< n

  • edges[i] ≠\neq i

  • 0≤0 \leq node1, node2 <n< n