The Shortest Cycle in a Graph interview question gives you an undirected graph with n nodes and a list of edges. Find the length of the shortest cycle in the graph. If no cycle exists, return -1. The shortest cycle is also called the "girth" of the graph. This is a BFS-based graph problem where you run BFS from each node to detect the shortest cycle passing through it.
Meta and Zomato ask this HARD graph problem because finding the girth of a graph has applications in network topology analysis, circuit design, and social network clustering. The naive approach tries all pairs, but the efficient solution runs BFS from each node to find the shortest cycle through it — O(n × (n + m)) overall. It tests deep BFS understanding and the ability to detect cycles by tracking distances.
The pattern is BFS from each node to find the shortest back edge. For each source node s, run BFS and track distances dist[v] from s. When you encounter an edge (u, v) where v is already visited and v != parent[u] (avoiding trivial back-edges in undirected graphs), the cycle length is dist[u] + dist[v] + 1. Take the minimum across all such back edges and all source nodes. If no back edge is ever found, return -1.
Graph: 0-1, 1-2, 2-3, 3-0, 0-2 (pentagon with diagonal).
BFS from node 0:
Shortest cycle: 3 (triangle 0-1-2-0).
dist[u] + dist[v] instead of dist[u] + dist[v] + 1 — the +1 accounts for the edge (u,v) itself.For the Shortest Cycle in a Graph coding problem, the BFS graph interview pattern for cycle detection and length measurement is the key. Run BFS from each node and detect back edges — the minimum dist[u] + dist[v] + 1 across all back edges gives the girth. Meta interviewers ask about the time complexity — O(n × (n + m)) in the worst case. Practice this "BFS to measure cycle length" pattern alongside the standard cycle detection algorithms. It's particularly valuable in competitive programming and graph theory interview rounds.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Shortest Path with Alternating Colors | Medium | Solve | |
| Maximum Candies You Can Get from Boxes | Hard | Solve | |
| Second Minimum Time to Reach Destination | Hard | Solve | |
| Reorder Routes to Make All Paths Lead to the City Zero | Medium | Solve | |
| Keys and Rooms | Medium | Solve |