Data Structures & AlgorithmsVery hardProduct-company MCQ pattern
A directed graph has edges E→A, C→D, D→B, C→E, 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. No, it is a DAG
- D. Cannot be determined without running BFS
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
- An undirected graph has adjacency lists (neighbours visited in alphabetical order) A: [B]; B: [A, C, F]; C: [B, E, F]; D: [F]; E: [C]; F…
- A binary tree has preorder traversal [90, 24, 42, 38, 77, 67, 57, 44] and inorder traversal [24, 38, 42, 44, 57, 67, 77, 90]…
- A binary tree has preorder traversal [9, 97, 20, 59, 28, 78] and inorder traversal [9, 20, 28, 59, 78, 97]. Reconstructing the tree (root…
- Keys 55, 72, 25, 37, 27, 49, 91 are inserted via separate chaining (h(k) = k mod 7, new keys appended to the end of the chain) into a…
- An undirected graph has edges (u–v: weight) A–B:4, B–D:7, A–D:15, A–C:29, B–C:28, C–D:29. What is the weight of its minimum spanning tree?
- Keys 27, 96, 68, 47, 51, 92, 12 are inserted in this order into an empty BST (no rebalancing). What is the height of the tree (edges on…