Skip to the code
+50 XP

#414 Shortest Loop in a Network

hard

A network team wants to know how short the tightest loop of cables is, because short loops cause broadcast storms. Devices are numbered 0 to n - 1, and cables[i] = [a, b] connects a and b (both ways).

Write shortestLoop(n, cables) that returns the number of cables in the shortest loop: a path that starts and ends at the same device, uses at least 3 cables, and never repeats a cable or a device (other than returning to the start). Return -1 if the network has no loop.

No cable is listed twice, and no cable connects a device to itself.

Example 1

Input: n = 6, cables = [[0,1],[1,2],[2,0],[2,3],[3,4],[4,5],[5,2]]
Output: 3

The triangle 0-1-2 uses 3 cables. The loop 2-3-4-5 uses 4.

Example 2

Input: n = 4, cables = [[0,1],[1,2],[1,3]]
Output: -1

These cables form a tree, so there is no loop.

Constraints

  • 2 <= n <= 300
  • 0 <= cables.length <= 2000
  • 0 <= a, b < n, a !== b
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).