Data Structures & AlgorithmsVery hardAmazon/Microsoft SDE pattern
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), does this graph contain a cycle?
- A. Yes, it has a cycle
- B. Yes, but only a self-loop
- C. Cannot be determined without running BFS
- D. No, it is a DAG
Correct answer: D. No, it is a DAG
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: "No, it is a DAG". 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
- 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)…
- An undirected connected graph has edges A–B, B–C, C–D, D–E, E–F, F–G, G–H, C–G, A–C. How many articulation points (cut vertices) and how…
- What are the time complexities of P and Q? c int P(int n) { if (n <= 1) return 1; return P(n/2) + P(n/2) + P(n/2) + P(n/2) + n; } int…
- A trie is built from the words {den, dog, car, card, do, cat, deer}. Using the trie (walk the prefix's characters, then count all words in…