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 in a Graph INPUT 0 2 1 edges array: [0,1] [1,2] [2,0] n = 3 vertices Bi-directional graph Find shortest cycle ALGORITHM (BFS) 1 Build adjacency list 0: [1,2], 1: [0,2], 2: [1,0] 2 BFS from each node Track distance from start 3 Detect cycle When neighbor already visited 4 Calculate cycle length dist[u] + dist[v] + 1 BFS from node 0: 0 d=0 1 d=1 2 d=1 Cycle! 1+1+1=3 FINAL RESULT 0 2 1 Cycle: 0 --> 1 --> 2 --> 0 Output: 3 Shortest cycle has length 3 Key Insight: BFS from each vertex finds shortest path to all other vertices. When we encounter an already-visited neighbor (not parent), we found a cycle. Its length = dist[current] + dist[neighbor] + 1. Time: O(V * (V + E)) | Space: O(V + E). Track minimum across all BFS runs. TutorialsPoint - Shortest Cycle in a Graph | BFS Approach
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