## Similar Problems

Similar Problems not available

# Find Closest Node To Given Two Nodes - Leetcode Solution

## Companies:

LeetCode: Find Closest Node To Given Two Nodes Leetcode Solution

Difficulty: Medium

Topics: depth-first-search graph

Problem Statement:

You are given a graph consisting of n nodes represented by an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi.

You are also given two different nodes start and end.

Return the closest node to start that is directly connected to end. Note that there can be multiple answers for this question.

It is guaranteed that there exists a path between start and end.

Approach:

We can use BFS to find the shortest path from start to end, then we can backtrace this path to find the closest node directly connected to end.

First, we will build an adjacency list to represent the graph.

Then, we will run BFS from start node and keep track of the distance of each node from start.

Once we reach the end node, we will backtrace using the parent array to find the closest nodes that are directly connected to end.

Solution:

Here is the Python implementation of the above approach:

from collections import defaultdict from queue import Queue

class Solution: def findClosest(self, n: int, edges: List[List[int]], start: int, end: int) -> int: # build adjacency list adj_list = defaultdict(list) for u, v in edges: adj_list[u].append(v) adj_list[v].append(u)

```
# BFS to find shortest path from start to end
visited = [False] * n
parent = [-1] * n
distance = [-1] * n
q = Queue()
q.put(start)
visited[start] = True
distance[start] = 0
while not q.empty():
u = q.get()
for v in adj_list[u]:
if not visited[v]:
visited[v] = True
parent[v] = u
distance[v] = distance[u] + 1
q.put(v)
# termination condition
if v == end:
return self.closestNode(adj_list, parent, end)
def closestNode(self, adj_list, parent, end):
# backtrace path from end to start
nodes = []
node = end
while node != -1:
nodes.append(node)
node = parent[node]
# find closest node directly connected to end
min_distance = float('inf')
closest_node = -1
for node in nodes:
for neighbor in adj_list[node]:
if neighbor in nodes:
if distance := abs(neighbor - node) < min_distance:
min_distance = distance
closest_node = neighbor
return closest_node
```

The time complexity of the above solution is O(n) for building the adjacency list, O(n) for BFS, and O(n) for backtracing the path. Therefore, the overall time complexity is O(n).

The space complexity is O(n) for the adjacency list, visited, parent, and distance arrays. Therefore, the overall space complexity is O(n).

## Find Closest Node To Given Two Nodes Solution Code

`1`