Data Structures & AlgorithmsVery hardAmazon/Microsoft SDE pattern
A directed graph has edges E→C, B→E, A→E, C→A, B→C, A→D, E→D. 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. No, it is a DAG
- C. Cannot be determined without running BFS
- D. Yes, but only a self-loop
Correct answer: A. 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 binary tree has preorder traversal [75, 38, 23, 7, 60, 94, 80, 95] and inorder traversal [7, 23, 38, 60, 75, 80, 94, 95]. Reconstructing…
- Undirected graph edges: D–A, D–B, A–C, B–C, A–B, D–C. Using a BFS 2-colouring, is this graph bipartite?
- Keys 18, 24, 4, 33, 84, 49, 74, 69, 8, 79 are inserted via separate chaining (h(k) = k mod 8, new keys appended to the end of the chain)…
- Undirected graph edges: E–B, A–D, A–C, A–B, B–D. Using a BFS 2-colouring, is this graph bipartite?
- A directed graph has edges C→A, B→D, D→B, D→C, D→A. Using 3-colour DFS (white/grey/black, a grey-to-grey back edge means a cycle), does…
- 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…