Data Structures & AlgorithmsVery hardAmazon/Microsoft SDE pattern

A directed graph has edges E→C, B→E, A→E, C→A, B→C, A→D, E→D. Using 3-colour DFS (white/grey/black, a grey-to-grey back edge means a cycle), does this graph contain a cycle?

  1. A. Yes, it has a cycle
  2. B. No, it is a DAG
  3. C. Cannot be determined without running BFS
  4. D. Yes, but only a self-loop

Correct answer: A. Yes, it has a cycle

DFS marks a vertex grey while it's on the current recursion stack and black once fully explored; finding an edge into a grey vertex means a back edge, i.e. a cycle. Running this on the given edges gives: "Yes, it has a cycle". An edge into an already-black vertex is a forward/cross edge and does not indicate a cycle by itself.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic