Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Detect Cycles in Directed Graph

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Detect Cycles in Directed Graph. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Given a directed graph with n nodes labeled from 0 to n - 1 and a list of directed edges edges, determine whether the graph contains a cycle. Return True if any cycle exists and False otherwise. The graph may be disconnected.

Constraints

  • 1 <= n <= 10^5
  • 0 <= edges.length <= 2 * 10^5
  • 0 <= u, v < n for every edge [u, v]
  • Self-loops and duplicate edges may appear

Function Signature

def has_cycle(n, edges):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output