Skip to the code
+25 XP

#435 Degrees Between Two Users

medium

A professional network shows "you are 3 connections away" on profiles. Users are numbered 0 to n - 1, and connections[i] = [a, b] means a and b are connected (both ways).

Write degreesApart(n, connections, a, b) that returns the fewest connections on a path from user a to user b, or -1 if there is no path. If a === b, return 0. The network is large, so try to search from both ends.

Example 1

Input: n = 6, connections = [[0,1],[1,2],[2,3],[3,4],[0,5],[5,4]], a = 0, b = 3
Output: 3

Both 0-1-2-3 and 0-5-4-3 use 3 connections.

Example 2

Input: n = 4, connections = [[0,1],[2,3]], a = 0, b = 3
Output: -1

Users 0 and 3 are in separate parts of the network.

Constraints

  • 1 <= n <= 100000
  • 0 <= connections.length <= 200000
  • 0 <= a, b < n
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).