Detect cycle in a directed graph
AmazonSoftware Engineer · OnsiteLast updated
This question evaluates mastery of graph algorithms and graph theory concepts—specifically directed cycle detection—and assesses the ability to reason about algorithmic correctness and to analyze time and space complexity for competing approaches.
Given a directed graph represented by an adjacency list with n vertices and m edges, determine whether the graph contains a cycle. Describe and implement an algorithm that returns true if a cycle exists and false otherwise. Explain the time and space complexity, and discuss both a DFS-based approach using a recursion stack and an approach based on Kahn’s topological sort.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.