#2359
Find Closest Node to Given Two Nodes
MediumDepth-First SearchGraph TheoryBFSGraph TraversalDistance Calculation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can use Breadth-First Search (BFS) to efficiently find the shortest distance from both nodes to all reachable nodes. This way, we avoid redundant calculations and can directly find the minimum maximum distance.
⚙️
Algorithm
4 steps- 1Step 1: Use BFS to find the shortest distance from node1 to all reachable nodes and store them in a distance array.
- 2Step 2: Use BFS again to find the shortest distance from node2 to all reachable nodes and store them in another distance array.
- 3Step 3: Iterate through both distance arrays to find the common nodes and calculate the maximum distance for each common node.
- 4Step 4: Track the node with the smallest maximum distance, and if there are ties, choose the smallest index.
solution.py31 lines
1# Full working Python code
2
3def find_closest_node(edges, node1, node2):
4 from collections import deque
5
6 def bfs(start):
7 distances = [-1] * len(edges)
8 queue = deque([start])
9 distances[start] = 0
10 while queue:
11 current = queue.popleft()
12 next_node = edges[current]
13 if next_node != -1 and distances[next_node] == -1:
14 distances[next_node] = distances[current] + 1
15 queue.append(next_node)
16 return distances
17
18 dist1 = bfs(node1)
19 dist2 = bfs(node2)
20
21 min_max_distance = float('inf')
22 result_node = -1
23
24 for node in range(len(edges)):
25 if dist1[node] != -1 and dist2[node] != -1:
26 max_distance = max(dist1[node], dist2[node])
27 if max_distance < min_max_distance or (max_distance == min_max_distance and node < result_node):
28 min_max_distance = max_distance
29 result_node = node
30
31 return result_nodeℹ
Complexity note: This complexity arises because we perform BFS twice, each taking linear time relative to the number of nodes.
- 1Using BFS allows us to efficiently find distances in a directed graph.
- 2Minimizing the maximum distance helps in finding the optimal node.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.