What is the main idea behind Topological Sort using DFS?
We visit each node and explore all its neighbors before adding the node to the result. This way, nodes appear after all their dependencies in the final order.
Click to reveal answer
beginner
Why can Topological Sort only be applied to Directed Acyclic Graphs (DAGs)?
Because if there is a cycle, there is no way to order nodes so that every node comes after its dependencies. Cycles create impossible ordering.
Click to reveal answer
intermediate
In DFS-based Topological Sort, when do we add a node to the output list?
We add the node after visiting all its neighbors (i.e., when the DFS call for that node finishes). This ensures dependencies come first.
Click to reveal answer
intermediate
What data structure is commonly used to store the final topological order in DFS approach?
A stack or a list where nodes are pushed after their DFS completes. Reversing this list gives the topological order.
Click to reveal answer
advanced
How does DFS help detect cycles during Topological Sort?
By tracking nodes currently in the recursion stack, if we revisit a node in this stack, it means a cycle exists.
Click to reveal answer
What type of graph is required for Topological Sort using DFS?
ADirected Acyclic Graph (DAG)
BUndirected Graph
CAny Graph
DCyclic Graph
✗ Incorrect
Topological Sort only works on Directed Acyclic Graphs because cycles prevent a valid ordering.
When do we add a node to the result list in DFS-based Topological Sort?
ARandomly
BBefore visiting neighbors
CWhen first discovered
DAfter visiting all neighbors
✗ Incorrect
We add nodes after visiting all neighbors to ensure dependencies come first.
What does a cycle in the graph mean for Topological Sort?
ASort is possible
BSort is impossible
CSort is faster
DSort is optional
✗ Incorrect
Cycles make it impossible to order nodes so that dependencies come first.
Which data structure helps detect cycles during DFS?
ARecursion stack
BPriority queue
CQueue
DVisited set only
✗ Incorrect
The recursion stack tracks nodes in the current path to detect cycles.
What is the time complexity of Topological Sort using DFS?
AO(E^2)
BO(V^2)
CO(V + E)
DO(1)
✗ Incorrect
DFS visits each vertex and edge once, so time complexity is O(V + E).
Explain how DFS is used to perform Topological Sort on a graph.
Think about visiting dependencies before the node itself.
You got /5 concepts.
Describe how cycle detection works during DFS in Topological Sort.
Focus on nodes currently being explored.
You got /3 concepts.
Practice
(1/5)
1. What is the main purpose of using DFS in Topological Sort on a directed graph?
easy
A. To detect cycles in an undirected graph
B. To find the shortest path between two nodes
C. To visit nodes in a way that all dependencies come before the node
D. To count the number of connected components
Solution
Step 1: Understand DFS role in Topological Sort
DFS visits nodes deeply, ensuring all nodes reachable from a node are visited first.
Step 2: Relation to dependencies
In Topological Sort, DFS ensures nodes are added after all their dependencies (incoming edges) are processed.
Final Answer:
To visit nodes in a way that all dependencies come before the node -> Option C
Quick Check:
DFS orders nodes respecting dependencies [OK]
Hint: DFS visits dependencies before the node itself [OK]
Common Mistakes:
Confusing DFS with BFS for topological order
Thinking DFS finds shortest paths
Mixing cycle detection with topological sorting
2. Which of the following Rust code snippets correctly declares a recursive DFS function for topological sort?
easy
A. fn dfs(node: usize, graph: &Vec, visited: Vec<bool>, stack: &mut Vec<usize>) { /* body */ }
B. fn dfs(node: usize, graph: &Vec, visited: &mut Vec<bool>, stack: &mut Vec<usize>) { /* body */ }
C. fn dfs(node: &usize, graph: &Vec<usize>, visited: &Vec<bool>, stack: &Vec<usize>) { /* body */ }
D. fn dfs(node: usize, graph: Vec, visited: Vec<bool>, stack: Vec<usize>) { /* body */ }
Solution
Step 1: Check parameter passing for DFS
Graph and visited must be passed by reference to avoid copying; stack must be mutable reference to push nodes.
Step 2: Analyze options
fn dfs(node: usize, graph: &Vec, visited: &mut Vec<bool>, stack: &mut Vec<usize>) { /* body */ } passes graph and visited by reference and stack as mutable reference, correct for DFS recursion.
Final Answer:
fn dfs(node: usize, graph: &Vec, visited: &mut Vec<bool>, stack: &mut Vec<usize>) { /* body */ } -> Option B
Quick Check:
Correct references and mutability in parameters [OK]
Hint: Pass graph and visited by reference, stack as mutable reference [OK]
Common Mistakes:
Passing graph or visited by value causing copies
Not using mutable reference for stack
Incorrect types for graph adjacency list
3. Given the following graph edges: 0->1, 0->2, 1->3, 2->3, what is the topological order output by DFS-based topological sort starting from node 0?
fn main() {
let graph = vec![
vec![1, 2],
vec![3],
vec![3],
vec![],
];
let mut visited = vec![false; 4];
let mut stack = Vec::new();
dfs(0, &graph, &mut visited, &mut stack);
while let Some(node) = stack.pop() {
print!("{} ", node);
}
}
fn dfs(node: usize, graph: &Vec, visited: &mut Vec<bool>, stack: &mut Vec<usize>) {
if visited[node] { return; }
visited[node] = true;
for &neighbor in &graph[node] {
dfs(neighbor, graph, visited, stack);
}
stack.push(node);
}
medium
A. 0 2 1 3
B. 3 1 2 0
C. 0 1 2 3
D. 3 2 1 0
Solution
Step 1: Trace DFS calls and stack pushes
DFS starts at 0, visits 1, then 3 (push 3), back to 1 (push 1), then visits 2, then 3 (already visited), push 2, finally push 0.
Step 2: Stack content and output order
Stack after DFS: [3,1,2,0]. Popping gives 0 then 2 then 1 then 3, printing "0 2 1 3".
Final Answer:
0 2 1 3 -> Option A
Quick Check:
DFS post-order stack reversed = topological order [OK]
Hint: Stack push after recursion; pop reverses order [OK]
Common Mistakes:
Printing stack before reversing
Not marking visited nodes
Confusing order of push and pop
4. Identify the bug in this DFS-based topological sort code snippet:
fn dfs(node: usize, graph: &Vec, visited: &mut Vec<bool>, stack: &mut Vec<usize>) {
visited[node] = true;
for &neighbor in &graph[node] {
if !visited[neighbor] {
dfs(neighbor, graph, visited, stack);
}
}
stack.push(node);
}
fn main() {
let graph = vec![vec![1], vec![2], vec![0]];
let mut visited = vec![false; 3];
let mut stack = Vec::new();
for i in 0..3 {
if !visited[i] {
dfs(i, &graph, &mut visited, &mut stack);
}
}
while let Some(node) = stack.pop() {
print!("{} ", node);
}
}
medium
A. DFS does not mark nodes as visited
B. Visited vector is not initialized correctly
C. Stack is not cleared before use
D. The graph contains a cycle, so topological sort is invalid
Solution
Step 1: Analyze graph edges
Edges: 0->1, 1->2, 2->0 form a cycle.
Step 2: Understand topological sort limitation
Topological sort requires DAG (no cycles). Cycle presence makes ordering impossible.
Final Answer:
The graph contains a cycle, so topological sort is invalid -> Option D
Quick Check:
Cycle in graph prevents valid topological order [OK]
Hint: Check for cycles before topological sort [OK]
Common Mistakes:
Ignoring cycles in input graph
Assuming topological sort works on cyclic graphs
Not detecting cycles before sorting
5. You have a project with tasks and dependencies: Task 5 depends on 2 and 0, Task 4 depends on 0 and 1, Task 2 depends on 3, Task 3 depends on 1. Using DFS-based topological sort, which of these is a valid order to complete all tasks?
Tasks: 0,1,2,3,4,5
Dependencies:
- 5 -> 2,0
- 4 -> 0,1
- 2 -> 3
- 3 -> 1
Options:
A) 1 3 0 2 4 5
B) 1 2 3 0 4 5
C) 0 1 2 3 4 5
D) 3 1 0 2 4 5
hard
A. 1 3 0 2 4 5
B. 1 2 3 0 4 5
C. 0 1 2 3 4 5
D. 3 1 0 2 4 5
Solution
Step 1: Analyze dependencies order
Task 5 after 2 and 0; 4 after 0 and 1; 2 after 3; 3 after 1.
Step 2: Validate each option
1 3 0 2 4 5 respects all: 1 before 3, 3 before 2, 0 before 4 and 5, 2 and 0 before 5, 1 and 0 before 4.
Final Answer:
1 3 0 2 4 5 -> Option A
Quick Check:
All dependencies precede dependent tasks [OK]
Hint: Check all dependencies appear before dependent tasks [OK]
Common Mistakes:
Ignoring order of dependencies
Placing dependent tasks before prerequisites
Confusing task numbers and dependencies
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.