Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Detect Cycles in Directed Graph
00:00
5 left

Detect Cycles in Directed Graph

MediumPython

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):
Interviewer

Your question is Detect Cycles in Directed Graph. Start with the requirements in the Question tab.

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.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.