Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Directed Graph Cycle Detection
00:00
5 left

Directed Graph Cycle Detection

MediumPython

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

Your question is Directed Graph Cycle Detection. 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.