DSA Graphs

Shortest Cycle in a Graph

For each source node, BFS to find the shortest cycle including it — return the global minimum.

Hard
Time O(V*(V + E)) Space O(V)
LeetCode
5 min read
graph bfs girth

Problem#

Given an undirected graph as edge list, return the length of the shortest cycle (girth), or -1 if acyclic.

Examples#

  • n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]]3
  • n = 4, edges = [[0,1],[0,2]]-1

Constraints#

  • 2 <= n <= 1000, 1 <= edges.length <= 1000.

Approach#

For each source s, BFS and record dist. When relaxing edge (u, v), if v is already visited and is not the parent of u, a cycle exists of length dist[u] + dist[v] + 1. Track the minimum.

Solution#

Shortest Cycle in a Graph
class Solution {
public:
int findShortestCycle(int n, vector<vector<int>>& edges) {
vector<vector<int>> adj(n);
for (auto& e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
int best = INT_MAX;
for (int s = 0; s < n; ++s) {
vector<int> dist(n, -1), parent(n, -1);
dist[s] = 0;
queue<int> q;
q.push(s);
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v : adj[u]) {
if (dist[v] == -1) {
dist[v] = dist[u] + 1;
parent[v] = u;
q.push(v);
} else if (parent[u] != v) {
best = min(best, dist[u] + dist[v] + 1);
}
}
}
}
return best == INT_MAX ? -1 : best;
}
};

Editorial#

BFS from each source finds the shortest path within each connected component. A back-edge during BFS — visiting a node that’s already known but isn’t the parent — closes a cycle whose length is dist[u] + dist[v] + 1. The parent check rules out trivial 2-cycles from undirected edges.

Complexity#

  • Time: O(V*(V + E)).
  • Space: O(V).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.