Skip to content

Practice Shortest Cycle in a Graph

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#2608
LeetCode Problem

Shortest Cycle in a Graph

Problem Statement

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.

Source: Shortest Cycle in a Graph on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]]
Output
3

# Example 2

Input
n = 4, edges = [[0,1],[0,2]]
Output
-1

Constraints

2 <= n <= 1000
1 <= edges.length <= 1000
edges[i].length == 2
0 <= ui, vi < n
ui != vi
There are no repeated edges.

Related LeetCode Problems

Practice more problems similar to Shortest Cycle in a Graph.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.