Tap here to switch tabs
Problem
Submissions

Problem: Shortest Cycle in a Graph

hard
40 min
Explore how to find the shortest cycle in a bidirectional graph by analyzing edges and vertices. Learn to detect cycles and solve graph problems by applying key graph theory concepts and algorithms.

Statement

You are given a bidirectional graph with n vertices, labeled from 0 to n - 1. The graph is represented by a 2D integer array edges, where each element edges[i] = [ui, vi] represents an edge connecting vertex ui and vertex vi. Each vertex pair has at most one edge between them, and no vertex is connected to itself.

Your task is to find the length of the shortest cycle in the graph. A cycle is defined as a path that starts and ends at the same vertex, with each edge in the path appearing exactly once. If no cycle exists in the graph, return -1.

Constraints:  

  • 22 \leq n 1000\leq 1000

  • 11 \leq edges.length 1000\leq 1000

  • edges.length ==2 == 2

  • 00 \leq ui, vi << n  

  • ui \neq vi

  • No duplicate edges exist in the graph

Unlock AI-Powered LearningUpgrade to smarter learning with instant explanations of Ask Agent, Personalized Interview Prep, Real-World Projects, 3 AI Mock Interviews per month, and Personalized Paths
Tap here to switch tabs
Problem
Submissions

Problem: Shortest Cycle in a Graph

hard
40 min
Explore how to find the shortest cycle in a bidirectional graph by analyzing edges and vertices. Learn to detect cycles and solve graph problems by applying key graph theory concepts and algorithms.

Statement

You are given a bidirectional graph with n vertices, labeled from 0 to n - 1. The graph is represented by a 2D integer array edges, where each element edges[i] = [ui, vi] represents an edge connecting vertex ui and vertex vi. Each vertex pair has at most one edge between them, and no vertex is connected to itself.

Your task is to find the length of the shortest cycle in the graph. A cycle is defined as a path that starts and ends at the same vertex, with each edge in the path appearing exactly once. If no cycle exists in the graph, return -1.

Constraints:  

  • 22 \leq n 1000\leq 1000

  • 11 \leq edges.length 1000\leq 1000

  • edges.length ==2 == 2

  • 00 \leq ui, vi << n  

  • ui \neq vi

  • No duplicate edges exist in the graph

Unlock AI-Powered LearningUpgrade to smarter learning with instant explanations of Ask Agent, Personalized Interview Prep, Real-World Projects, 3 AI Mock Interviews per month, and Personalized Paths