Skip to the solution
MediumDSA12 min read

How do you detect a cycle in a directed graph?

999 views

The problem

Question presented to candidate: "Given a directed graph with n nodes and a list of edges, tell me whether it contains a cycle. If you can, return one cycle as a list of nodes. Please code it in Python."

What a strong answer should cover:

  • Why a single "visited" flag gives false positives in a directed graph (a diamond is not a cycle).
  • Three-colour DFS: WHITE/GRAY/BLACK, a cycle exactly when an edge reaches a GRAY node (a back edge), and why BLACK nodes are safe.
  • Restarting DFS from every unvisited node, self-loops, and recovering the cycle from the current path.
  • O(V + E) time and O(V) extra space, with Kahn's algorithm as the non-recursive alternative.
  • Python specifics: a nested visit function closing over a color list, any(...) over start nodes, the 1000-frame default recursion limit, and returning the cycle with list slicing.

Clarifying questions expected:

  • "Do you need just true/false, or the cycle itself?"
  • "Can there be self-loops, and is the graph connected?"

Code / implementation expected: Yes โ€” a three-colour DFS hasCycle (ideally returning the cycle) in Python.

  • graphs
  • cycle

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonThree-colour DFS that labels every edge and returns the cycle
PythonWhy one visited flag is wrong: naive vs three colours vs Kahn

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 50 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you check if a graph is bipartite?

Continue