MediumNo. 2359

Find Closest Node to Given Two Nodes — LeetCode 2359 Python Solution

Topics
Depth-First Search, Graph
Reading time
5 min

The problem

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].

Example

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.

Python solution

PythonSolution
class Solution:
    def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int:
        def f(i):
            dist = [inf] * n
            dist[i] = 0
            q = deque([i])
            while q:
                i = q.popleft()
                for j in g[i]:
                    if dist[j] == inf:
                        dist[j] = dist[i] + 1
                        q.append(j)
            return dist

        g = defaultdict(list)
        for i, j in enumerate(edges):
            if j != -1:
                g[i].append(j)
        n = len(edges)
        d1 = f(node1)
        d2 = f(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 ans

Complexity

Time
O(V+E)
Space · auxiliary
O(n)where n is the number of nodes

Pattern: Depth-First Search

Follow one path to its end before trying the next — the default way to explore a graph. LeetCode 2359. Find Closest Node to Given Two Nodes is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Depth-First Search and Graph.

The depth-first search guide has the Python template for the pattern and the 366 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
2360Longest Cycle in a GraphHard
0207Course ScheduleMedium
0210Course Schedule IIMedium
0310Minimum Height TreesMedium
0332Reconstruct ItineraryHard
0399Evaluate DivisionMedium

Frequently asked questions

How hard is LeetCode 2359. Find Closest Node to Given Two Nodes?

LeetCode 2359. Find Closest Node to Given Two Nodes is rated Medium on LeetCode.

What is the time complexity of LeetCode 2359. Find Closest Node to Given Two Nodes?

The Python solution on this page runs in O(V+E).

What is the space complexity of LeetCode 2359. Find Closest Node to Given Two Nodes?

The Python solution on this page uses O(n), where n is the number of nodes auxiliary space.

What topics does LeetCode 2359. Find Closest Node to Given Two Nodes cover?

LeetCode 2359. Find Closest Node to Given Two Nodes is tagged Depth-First Search and Graph on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.