Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Implement Directed Graph Cycle Detection

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

Your question is Implement 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

Implement a function in Python to detect a cycle in a directed graph, where the graph represents network connections between routers.

Use an adjacency list, where graph[i] contains the router indices directly reachable from router i. Return True if any directed cycle exists, including a self-loop, and False otherwise.

Function signature: def has_cycle(graph):. The input is a list of lists of integers, and the output is a Boolean.

Constraints

  • 0 <= len(graph) <= 1000
  • Each neighbor is an integer in the range 0 to len(graph) - 1
  • The graph may contain disconnected components
  • The graph may contain parallel directed edges
  • Return only a Boolean value

Function Signature

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