Shortest Cycle in a Graph - Problem

Imagine you're exploring a network of interconnected cities where roads are bi-directional and you want to find the shortest circular route that brings you back to where you started.

Given an undirected graph with n vertices labeled from 0 to n-1, represented by a 2D array edges where edges[i] = [ui, vi] indicates a bidirectional connection between vertices ui and vi, your task is to find the length of the shortest cycle.

Key constraints:

  • Each pair of vertices has at most one direct edge
  • No vertex connects to itself (no self-loops)
  • A cycle must use each edge exactly once

Return the length of the shortest cycle, or -1 if no cycle exists.

Example: In a graph with edges [[0,1],[1,2],[2,0],[2,3]], the shortest cycle is 0→1→2→0 with length 3.

Input & Output

example_1.py — Simple Triangle
$ Input: n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[6,3]]
Output: 3
💡 Note: The shortest cycle is 0 → 1 → 2 → 0 with length 3. There are other components in the graph but they don't form cycles.
example_2.py — No Cycle
$ Input: n = 4, edges = [[0,1],[0,2]]
Output: -1
💡 Note: The graph is a tree (no cycles exist), so we return -1.
example_3.py — Multiple Cycles
$ Input: n = 6, edges = [[0,1],[1,2],[2,3],[3,0],[2,4],[4,5],[5,2]]
Output: 3
💡 Note: There are two cycles: 0→1→2→3→0 (length 4) and 2→4→5→2 (length 3). The shortest is length 3.

Constraints

  • 2 ≤ n ≤ 1000
  • 1 ≤ edges.length ≤ min(2000, n * (n - 1) / 2)
  • edges[i].length == 2
  • 0 ≤ ui, vi ≤ n - 1
  • ui ≠ vi
  • No repeated edges between the same pair of vertices

Visualization

Tap to expand
STARTDistance: 0ADist: 1BDist: 1CDist: 2DDist: 2🔄 CYCLE DETECTED!Length = Dist(D) + Dist(START) + 1 = 2 + 0 + 1 = 3BFS Levels:● Level 0: START● Level 1: A, B● Level 2: C, D● Back edge: D → START
Understanding the Visualization
1
Choose starting intersection
Pick any vertex as the starting point for BFS exploration
2
Explore direct neighbors (Level 1)
Visit all vertices directly connected to the start, marking their distance as 1
3
Explore next level (Level 2)
From level 1 vertices, explore their unvisited neighbors at distance 2
4
Detect back edge
When we find an edge to a previously visited vertex (not our parent), we've found a cycle
5
Calculate cycle length
Cycle length = distance to current vertex + distance to found vertex + 1
Key Takeaway
🎯 Key Insight: BFS naturally finds shortest paths, so the first cycle we detect from any starting vertex is guaranteed to be the shortest cycle containing that vertex.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
52.3K Views
Medium Frequency
~25 min Avg. Time
1.8K 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