Shortest Cycle in a Graph - Problem

There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1. The edges in the graph are represented by a given 2D integer array edges, where edges[i] = [ui, vi] denotes an edge between vertex ui and vertex vi.

Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.

Return the length of the shortest cycle in the graph. If no cycle exists, return -1.

A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.

Input & Output

Example 1 — Simple Triangle
$ Input: edges = [[0,1],[1,2],[2,0]]
Output: 3
💡 Note: The graph forms a triangle: 0→1→2→0. This cycle has length 3, which is the shortest possible cycle.
Example 2 — Multiple Cycles
$ Input: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]
Output: 4
💡 Note: There's a 4-cycle: 1→2→3→4→1, and vertex 5 is connected but doesn't form a shorter cycle.
Example 3 — No Cycle
$ Input: edges = [[1,2],[2,3],[3,4]]
Output: -1
💡 Note: This is a simple path with no cycles, so return -1.

Constraints

  • 2 ≤ n ≤ 1000
  • 1 ≤ edges.length ≤ n * (n - 1) / 2
  • edges[i].length == 2
  • 0 ≤ ui, vi ≤ n - 1
  • ui != vi
  • There are no repeated edges

Visualization

Tap to expand
Shortest Cycle Detection in Undirected GraphInput: edges = [[0,1],[1,2],[2,0]]012Edge 1Edge 2Edge 3BFS Detection012Cycle: 0→1→2→0Length: 3Output: 3
Understanding the Visualization
1
Input Graph
Undirected graph with edges [[0,1],[1,2],[2,0]]
2
Find Cycles
Use BFS to detect cycles and measure their lengths
3
Return Shortest
Return the length of the shortest cycle found
Key Takeaway
🎯 Key Insight: BFS from each vertex guarantees finding the shortest cycle containing that vertex
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
18.5K Views
Medium Frequency
~25 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen