KatInterview

Find Minimum Network Distance Between Users

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

Last 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 0 if src == dst.
  • Return 1 if dst is a direct neighbor of src.
  • Return 2 if reaching dst requires navigating through one intermediate user, and so on.
  • Return -1 if there is no path connecting src to dst.

Constraints

  • 1 <= n <= 100,000
  • 0 <= len(connections) <= 200,000
  • 0 <= connections[i][0], connections[i][1] < n
  • 0 <= 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.