Data Structures & AlgorithmsHardTCS NQT · Infosys pattern
A directed graph has edges D→B, C→D, A→B, D→C. Using 3-colour DFS (white/grey/black, a grey-to-grey back edge means a cycle), does this graph contain a cycle?
- A. No, it is a DAG
- B. Cannot be determined without running BFS
- C. Yes, but only a self-loop
- D. Yes, it has a cycle
Correct answer: D. 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.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- A disjoint-set (union-find with union by rank and path compression) over 7 elements (0 to 6), each initially its own component, runs this…
- A disjoint-set (union-find with union by rank and path compression) over 8 elements (0 to 7), each initially its own component, runs this…
- A directed graph has edges B→E, E→A, E→C, B→A, E→D, D→C. Using 3-colour DFS (white/grey/black, a grey-to-grey back edge means a cycle)…
- What are the time complexities of P and Q? c int P(int n) { if (n <= 1) return 1; return return P(n/2) + n; } int Q(int n) { if (n <= 1)…
- A directed graph has edges E→A, D→A, D→E, B→D, D→C. Using 3-colour DFS (white/grey/black, a grey-to-grey back edge means a cycle), does…
- Keys 49, 39, 29 are inserted in this order into an empty AVL tree. After AVL rebalancing (a single rotation resolves the imbalance here)…