794. Shortest Loop

Hard7.5 points estimatedGraphBreadth-First Search3 hints

A theme park has n plazas numbered 0 to n - 1. Each entry [a, b] of edges is a footpath you can walk in both directions between plazas a and b. Two plazas are never joined by more than one footpath, and no footpath starts and ends at the same plaza.

A loop walk starts at some plaza, follows footpaths without using the same plaza twice (apart from returning to the start at the end), and finishes at its starting plaza. Its length is the number of footpaths it uses, and every loop walk has length at least 3. Return the length of the shortest loop walk anywhere in the park, or -1 if the park has no loop walk at all. The park may be split into several disconnected areas.

Example 1

Input:
n = 8edges = [[0,1],[1,2],[2,3],[3,4],[4,0],[2,5],[5,6],[6,2]]
Output:
3
Explanation:

Nodes 2, 5 and 6 form a loop of 3 lines, shorter than the 5-line loop 0-1-2-3-4.

Example 2

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

The only loop is 0-1-2-3, which has 4 lines; the branch 3-4-5 is not part of any loop.

Example 3

Input:
n = 5, edges = [[0,2],[2,4],[2,3],[1,2]]
Output:
-1
Explanation:

The network is a tree, so no loop exists and the answer is -1.

Constraints

  • 1 ≤ n ≤ 1500
  • 0 ≤ edges.length ≤ 3000
  • 0 ≤ a, b < n and a ≠ b
  • No pair of plazas is joined twice.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n * (n + m))
Space
O(n + m)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…