KatInterview

Minimum Degrees of Separation in a Social Network

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsbfsgraphshortest-path

Last 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_user and end_user, or -1 if 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