oneby7

Graphs Cycle detection

454. Cycle in a Directed Graph

Medium

You are given a directed graph with n vertices, numbered from 0 to n - 1. Each pair [u, v] in edges is an edge from vertex u to vertex v. An edge can be followed only in its own direction, from u to v.

A cycle is a path that follows one or more edges and ends at the vertex where it started. An edge from a vertex to itself, [u, u], is a cycle of one edge.

Return true if the graph has at least one cycle, and false if it has none.

Example 1

012345

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

Output: true

Explanation: The path 1 → 2 → 3 → 1 ends where it started. Vertices 0, 4 and 5 are on no cycle, but one cycle is enough.

Example 2

0123

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

Output: false

Explanation: Vertex 3 can be reached from 0 in two ways, through 1 and through 2. But no edge leaves vertex 3, and no path ever comes back to the vertex where it started.

Example 3

012

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

Output: true

Explanation: The edge [2,2] goes from vertex 2 back to itself, which is a cycle of one edge.

Check your understanding

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

n = 3, edges = [[0, 1], [1, 2], [0, 2]]

Constraints

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

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.