Shortest Cycle in a Graph — LeetCode 2608 Python Solution

HardBreadth-First SearchGraph
Problem
#2608
Reading time
4 min

The 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.

Example

Input
n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]]
Output
3
Explanation
The cycle with the smallest length is : 0 -> 1 -> 2 -> 0

Python solution

Python
class Solution:
    def findShortestCycle(self, n: int, edges: List[List[int]]) -> int:
        def bfs(u: int, v: int) -> int:
            dist = [inf] * n
            dist[u] = 0
            q = deque([u])
            while q:
                i = q.popleft()
                for j in g[i]:
                    if (i, j) != (u, v) and (j, i) != (u, v) and dist[j] == inf:
                        dist[j] = dist[i] + 1
                        q.append(j)
            return dist[v] + 1

        g = defaultdict(set)
        for u, v in edges:
            g[u].add(v)
            g[v].add(u)
        ans = min(bfs(u, v) for u, v in edges)
        return ans if ans < inf else -1

Complexity

MeasureComplexity
TimeO(m^2)
SpaceO(m + n), where m and n are the length of the array edges and the number of vertices auxiliary

Pattern: Breadth-First Search

Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 2608. Shortest Cycle in a Graph is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.

The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2608. Shortest Cycle in a Graph?
LeetCode 2608. Shortest Cycle in a Graph is rated Hard on LeetCode.
What is the time complexity of LeetCode 2608. Shortest Cycle in a Graph?
The Python solution on this page runs in O(m^2).
What is the space complexity of LeetCode 2608. Shortest Cycle in a Graph?
The Python solution on this page uses O(m + n), where m and n are the length of the array edges and the number of vertices auxiliary space.
What topics does LeetCode 2608. Shortest Cycle in a Graph cover?
LeetCode 2608. Shortest Cycle in a Graph is tagged Breadth-First Search and Graph on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview