Find Minimum Network Distance Between Users
Trees & GraphsAuto-graded · 21 test casesLast updated
Compute the shortest path distance between two nodes in an unweighted undirected graph using Breadth-First Search.
You are analyzing a social network consisting of $n$ users labeled from 0 to n - 1. Mutual connections between users are provided as an array of undirected edges connections, where connections[i] = [u, v] represents a direct bidirectional relationship between user u and user v.
Given two user labels, src and dst, calculate the shortest separation distance (the minimum number of connection steps required) to reach dst from src.
Return rules:
- Return
0ifsrc == dst. - Return
1ifdstis a direct neighbor ofsrc. - Return
2if reachingdstrequires navigating through one intermediate user, and so on. - Return
-1if there is no path connectingsrctodst.
Constraints
1 <= n <= 100,0000 <= len(connections) <= 200,0000 <= connections[i][0], connections[i][1] < n0 <= src, dst < n- Graph edges are undirected and may contain parallel edges or self-loops.
Examples
Example 1
Input: degrees_of_connection(5, [[0, 1], [1, 2], [2, 3], [3, 4]], 0, 4)
Output: 4
Example 2
Input: degrees_of_connection(5, [[0, 1], [1, 2], [2, 3], [3, 4]], 2, 2)
Output: 0
Example 3
Input: degrees_of_connection(6, [[0, 1], [1, 2], [3, 4]], 0, 4)
Output: -1
Hints
Hint 1
Because all connections have equal weight, a standard graph traversal layer-by-layer will guarantee finding the shortest path.
Hint 2
Consider using Breadth-First Search (BFS) starting from `src`. What data structures do you need to avoid reprocessing nodes?
Hint 3
Edge cases: address `src == dst` before starting the traversal, and handle parallel edges or self-loops smoothly using a visited tracker.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks for the minimum distance between two vertices in an unweighted, undirected graph. Breadth-First Search (BFS) is optimal here because it visits nodes in order of increasing distance from the start node src.
- Base Case Check: If
src == dst, return0immediately. - Adjacency List Construction: Store the graph connections using a list of lists. Since relationships are mutual, insert each edge in both directions.
- BFS Traversal:
- Maintain a
distancesarray initialized to-1for all nodes. This acts both as a tracker for visited nodes and to keep count of distance levels. - Set
distances[src] = 0and enqueuesrcinto a double-ended queue (deque). - While the queue is non-empty, dequeue the current node. For each neighbor:
- Skip the neighbor if it has already been visited (i.e.,
distances[neighbor] != -1). - If the neighbor is
dst, returndistances[current] + 1right away. - Otherwise, set
distances[neighbor] = distances[current] + 1and push the neighbor to the queue.
- Skip the neighbor if it has already been visited (i.e.,
- Maintain a
- Unreachable Case: If BFS finishes without encountering
dst, return-1.
Why It Is Correct
In an unweighted graph, BFS guarantees that when a node is first reached, the path taken to reach it has the minimum possible number of edges. Returning the distance upon discovering dst guarantees an accurate minimum distance without needing to explore remaining components.
Complexity Analysis
- Time Complexity: $\mathcal{O}(V + E)$, where $V = n$ is the number of nodes and $E = \text{len(connections)}$ is the number of edges. Each vertex and edge is processed a constant number of times.
- Space Complexity: $\mathcal{O}(V + E)$ to store the adjacency list representation of the graph, the distance array, and the BFS queue.
Reference Solution
from collections import deque
from typing import List
def degrees_of_connection(n: int, connections: List[List[int]], src: int, dst: int) -> int:
if src == dst:
return 0
graph = [[] for _ in range(n)]
for a, b in connections:
graph[a].append(b)
graph[b].append(a)
distances = [-1] * n
distances[src] = 0
queue = deque([src])
while queue:
person = queue.popleft()
next_distance = distances[person] + 1
for neighbor in graph[person]:
if distances[neighbor] != -1:
continue
if neighbor == dst:
return next_distance
distances[neighbor] = next_distance
queue.append(neighbor)
return -1