Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Directed Graph Cycle Detection

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

Your question is Directed Graph Cycle Detection. 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 0 to n - 1, determine whether the graph contains at least one cycle.

Implement a function that returns True if the graph has a cycle, otherwise return False.

Formal Specification

  • Input:
    • n, an integer representing the number of nodes.
    • edges, a list of directed edges, where each edge is a pair [u, v] meaning there is an edge from u to v.
  • Output:
    • Return a boolean value indicating whether the directed graph contains a cycle.

Constraints

  • 1 <= n <= 10^5
  • 0 <= len(edges) <= 2 * 10^5
  • 0 <= u, v < n
  • The graph may contain self-loops and parallel edges

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