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?
- A. Coloring is only needed for undirected graphs
- B. Any revisit of a previously seen node, finished or not, indicates a cycle
- 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
- 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
- Problem: A bipartite graph check is commonly done by attempting a 2-coloring via BFS/DFS. What does finding an edge between two…
- Problem: What is the time complexity of finding the lowest common ancestor (LCA) of two nodes in a binary tree with n nodes, using a…
- Problem: With O(n) preprocessing (Euler tour + sparse table for range-minimum query), LCA queries on a tree of n nodes can be answered in…
- Problem: Which statement correctly describes the diameter of a tree (the longest path between any two nodes) and how to compute it…
- Problem: A min-heap (binary heap) supports insert and extract-min in what time complexity, and what is the time to build a heap from n…
- Problem: To find the k largest elements among n numbers, which approach is asymptotically best when k is much smaller than n?