oneby7

Graphs Cycle detection

453. Cycle in an Undirected Graph

Medium

You are given an undirected graph with n vertices, numbered from 0 to n - 1. Each pair [u, v] in edges is an edge between vertices u and v, and it can be used in both directions.

Return true if the graph has a cycle, and false otherwise. A cycle is a way to leave a vertex along one edge and come back to it along another, without using any edge twice.

The graph can be in several pieces, with no edges between them. A cycle in any piece counts.

Example 1

012345

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

Output: true

Explanation: We can leave vertex 1 along the edge to 2, go on to 5, and come back to 1 along the edge [5,1]. Vertices 3 and 4 form a piece of their own, which does not change the answer.

Example 2

01234

Input: n = 5, edges = [[0, 2], [2, 4], [1, 3]]

Output: false

Explanation: Vertices 0, 2 and 4 form a path, and 1 and 3 are joined by a single edge. In both pieces, the only way back to a vertex is along the edge we just used.

Example 3

0

Input: n = 1, edges = []

Output: false

Check your understanding

Work out the answer for this input before you write any code.

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

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ edges.length ≤ 2 × 105
  • edges[i].length == 2
  • 0 ≤ ui, vi < n
  • ui ≠ vi
  • No edge appears twice: [u, v] and [v, u] are the same edge.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.