Ctrl K

Shortest Loop in a Network

Hard
A local network has n nodes numbered 0 to n - 1. The cables are listed in links: links[i] = [a, b] is a cable between nodes a and b that carries data both ways. Any two nodes share at most one cable, and no cable connects a node to itself. A loop is a route that leaves a node and comes back to it without using any cable twice. The length of a loop is the number of cables in it. Return the length of the shortest loop in the network, or -1 if there are no loops.
Example 1
n=5, links=[[0, 1], [1, 2], [2, 3], [3, 0], [1, 4]] → 4

The only loop, 0 → 1 → 2 → 3 → 0, uses four cables.

Example 2
n=6, links=[[0, 1], [1, 2], [2, 3], [3, 4], [4, 0], [1, 5], [5, 3], [2, 5]] → 3

There are loops of five and four cables, but the shortest ones are triangles, such as 1 → 2 → 5 → 1.

Example 3
n=4, links=[[0, 1], [1, 2], [1, 3]] → -1

The network is a tree, so it has no loops.

Constraints
  • 2 ≤ n ≤ 1000
  • 1 ≤ len(links) ≤ 1000
  • links[i] = [a, b], 0 ≤ a, b < n, a ≠ b
  • Any two nodes are joined by at most one cable
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLetter Order From a Dictionary HardLongest Uphill Walk HardBall Into the Hole HardThe Extra Link in a Rooted Tree HardPartners Side by Side Hard
loading Python…
Input
n=5, links=[[0, 1], [1, 2], [2, 3], [3, 0], [1, 4]]
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 65 tests on the server, hidden ones included.