Data Structures & AlgorithmsHardHCLTech · Wipro pattern
A directed graph has edges A→B, C→D, D→C, C→B. Using 3-colour DFS (white/grey/black, a grey-to-grey back edge means a cycle), does this graph contain a cycle?
- A. Cannot be determined without running BFS
- B. Yes, it has a cycle
- C. No, it is a DAG
- D. Yes, but only a self-loop
Correct answer: B. 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
- Build a binary min-heap in place from the array [73, 61, 88, 9, 29, 24, 58, 42] using bottom-up heapify (sift-down from the last internal…
- 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…
- 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)…