Minimum Degrees of Separation in a Social Network
Trees & GraphsAuto-graded · 18 test casesLast updated
Determine the shortest path distance between two nodes in an unweighted, undirected graph using Breadth-First Search.
You are given a list of bidirectional links in a social network. Each link is represented as a list of two integers [u, v], indicating that person u and person v are directly connected.
Given two target IDs, start_user and end_user, calculate the minimum degrees of separation (the minimum number of direct links needed to traverse from start_user to end_user).
If start_user and end_user are the same, the distance is 0. If there is no path connecting start_user and end_user, return -1.
Input
friendships: A list of pairs[u, v]of non-negative integers representing connected users.start_user: The integer ID of the starting user.end_user: The integer ID of the destination user.
Output
- An integer representing the minimum number of edge traversals between
start_userandend_user, or-1if no connection exists.
Constraints
- The total number of unique users $N$ is at most $100,000$.
- The total number of edges $E$ is at most $500,000$.
- User IDs are non-negative integers ($0 \le \text{ID} \le 10^9$).
Examples
Example 1
Input: find_shortest_path([[1, 2], [2, 3], [3, 4]], 1, 4)
Output: 3
Example 2
Input: find_shortest_path([[1, 2], [3, 4]], 1, 4)
Output: -1
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks for the minimum distance (in terms of edges) between two nodes in an unweighted, undirected graph.
- Edge Case: If
start_user == end_user, the distance is0. - Graph Representation: Build an adjacency list using a hash map where each key is a user ID mapping to a list of connected neighbors. Since connections are mutual, insert both directions
(u, v)and(v, u). - Check Existence: If
start_userorend_userhas no links infriendships, they will not exist in the adjacency list. If either is missing, no path can exist, so return-1. - Breadth-First Search (BFS):
- Initialize a queue with
start_userand track visited nodes along with their shortest distance fromstart_userusing a distance map. - Dequeue nodes layer by layer. For each neighbor of the current node, if it equals
end_user, returncurrent_distance + 1. - Otherwise, if the neighbor has not been visited, record its distance and push it to the queue.
- If the queue is exhausted without finding
end_user, return-1.
- Initialize a queue with
Complexity Analysis
- Time Complexity: $O(V + E)$, where $V$ is the number of distinct users and $E$ is the number of connection pairs. Building the graph takes $O(E)$ time. BFS visits each reachable vertex at most once and processes each edge twice (once from each end).
- Space Complexity: $O(V + E)$ to store the adjacency list representation, queue, and visited/distance map.
from collections import deque
from typing import List
def find_shortest_path(friendships: List[List[int]], start_user: int, end_user: int) -> int:
if start_user == end_user:
return 0
graph = {}
for a, b in friendships:
graph.setdefault(a, []).append(b)
graph.setdefault(b, []).append(a)
if start_user not in graph or end_user not in graph:
return -1
distances = {start_user: 0}
queue = deque([start_user])
while queue:
user = queue.popleft()
next_distance = distances[user] + 1
for neighbor in graph[user]:
if neighbor == end_user:
return next_distance
if neighbor not in distances:
distances[neighbor] = next_distance
queue.append(neighbor)
return -1