Data Structures & AlgorithmsVery hardTCS NQT Digital · Product Company SDE

Problem: Which best describes the relationship between DFS-based cycle detection in a directed graph and the 'white-gray-black' (or recursion-stack) coloring scheme?

  1. A. Coloring is only needed for undirected graphs
  2. B. Any revisit of a previously seen node, finished or not, indicates a cycle
  3. C. A back edge to a node currently on the recursion stack ('gray') indicates a cycle; an edge to an already-finished node ('black') does not
  4. D. Cycle detection in a directed graph needs no extra bookkeeping beyond a visited set

Correct answer: C. A back edge to a node currently on the recursion stack ('gray') indicates a cycle; an edge to an already-finished node ('black') does not

In directed graphs, visiting a node already fully explored ('black') is fine (it's just a shared descendant), but revisiting a node still on the current DFS path ('gray', i.e. an ancestor) means a back edge exists, which is exactly a cycle.

More Coding Interview Problems questions

Exams that ask this topic