Topological Sort Using DFS in DSA C# - Time & Space Complexity
We want to understand how the time needed to perform topological sort using DFS changes as the graph size grows.
Specifically, how the number of nodes and edges affects the work done.
Analyze the time complexity of the following code snippet.
void DFS(int node, Dictionary<int, List<int>> graph, HashSet<int> visited, Stack<int> stack) {
visited.Add(node);
foreach (var neighbor in graph[node]) {
if (!visited.Contains(neighbor)) {
DFS(neighbor, graph, visited, stack);
}
}
stack.Push(node);
}
void TopologicalSort(Dictionary<int, List<int>> graph) {
var visited = new HashSet<int>();
var stack = new Stack<int>();
foreach (var node in graph.Keys) {
if (!visited.Contains(node)) {
DFS(node, graph, visited, stack);
}
}
}
This code performs a topological sort on a directed graph using Depth-First Search (DFS).
Identify the loops, recursion, array traversals that repeat.
- Primary operation: DFS visits each node and explores all its neighbors recursively.
- How many times: Each node is visited exactly once, and each edge is explored once during the DFS calls.
As the number of nodes (n) and edges (e) increase, the DFS explores all nodes and edges once.
| Input Size (n, e) | Approx. Operations |
|---|---|
| 10 nodes, 15 edges | About 25 operations (10 nodes + 15 edges) |
| 100 nodes, 200 edges | About 300 operations (100 + 200) |
| 1000 nodes, 5000 edges | About 6000 operations (1000 + 5000) |
Pattern observation: The work grows roughly in proportion to the sum of nodes and edges.
Time Complexity: O(n + e)
This means the time needed grows linearly with the number of nodes plus the number of edges in the graph.
[X] Wrong: "DFS visits each node multiple times, so time complexity is higher than O(n + e)."
[OK] Correct: Each node is marked visited and processed only once, so DFS does not repeat work on the same node.
Understanding this time complexity helps you explain how graph algorithms efficiently handle dependencies and ordering.
"What if the graph is represented as an adjacency matrix instead of adjacency lists? How would the time complexity change?"
Practice
Solution
Step 1: Understand DFS role in Topological Sort
DFS visits nodes deeply, ensuring all nodes reachable from a node are visited before the node itself.Step 2: Relate DFS order to dependencies
In Topological Sort, nodes must appear after all their dependencies, which DFS achieves by post-order traversal.Final Answer:
To visit nodes in a way that all dependencies come before the node itself -> Option BQuick Check:
DFS ensures dependency order [OK]
- Confusing DFS with BFS for topological sorting
- Thinking DFS finds shortest paths
- Assuming DFS detects cycles in undirected graphs only
Dictionary?Solution
Step 1: Identify correct iteration over nodes
We must iterate over all keys (nodes) and call DFS only if not visited.Step 2: Check each option's correctness
foreach(var node in graph.Keys) if(!visited[node]) DFS(node); correctly iterates keys and checks visited. for(int i=0; i 0) DFS(graph.First().Key); modifies graph during iteration, unsafe. foreach(var node in graph.Values) DFS(node[0]); iterates values, not nodes.Final Answer:
foreach(var node in graph.Keys) if(!visited[node]) DFS(node); -> Option CQuick Check:
Iterate keys and check visited [OK]
- Iterating over graph.Values instead of Keys
- Assuming node indices are continuous from 0
- Modifying collection during iteration
var graph = new Dictionary {
{5, new List<int>{2,0}},
{4, new List<int>{0,1}},
{2, new List<int>{3}},
{3, new List<int>{1}},
{0, new List<int>()},
{1, new List<int>()}
};
var visited = new HashSet<int>();
var stack = new Stack<int>();
void DFS(int node) {
visited.Add(node);
foreach(var n in graph[node]) {
if(!visited.Contains(n)) DFS(n);
}
stack.Push(node);
}
foreach(var node in graph.Keys) {
if(!visited.Contains(node)) DFS(node);
}
var result = stack.ToArray();
Console.WriteLine(string.Join(", ", result));Solution
Step 1: Perform DFS and track stack push order
Start DFS from 5: visit 2, then 3, then 1; push 1, 3, 2, then 0 from 5's other edge; push 5. Then DFS from 4: visit 0 and 1 already visited, push 4.Step 2: Stack order and output
Stack push order is 1, 3, 2, 0, 5, 4. Converting stack to array reverses order: 4, 5, 0, 2, 3, 1.Final Answer:
4, 5, 0, 2, 3, 1 -> Option AQuick Check:
DFS post-order reversed = topological order [OK]
- Not reversing stack before output
- Visiting nodes in wrong order
- Ignoring nodes with no outgoing edges
void DFS(int node) {
visited.Add(node);
foreach(var n in graph[node]) {
if(!visited.Contains(n)) DFS(n);
}
stack.Push(node);
}
foreach(var node in graph.Keys) {
DFS(node);
}Solution
Step 1: Analyze potential runtime errors in DFS
When recursing to a neighbor n not present as a key in the graph (common for sink nodes), accessing graph[n] throws KeyNotFoundException.Step 2: Outer loop issue
Missing !visited check before DFS(node) causes duplicate stack pushes (logical error), not runtime error. Cycle detection needs separate recursion stack.Final Answer:
KeyNotFoundException because some nodes are missing in graph keys -> Option DQuick Check:
graph[n] for missing sink node key -> KeyNotFoundException [OK]
- Omitting sink/leaf nodes from graph keys
- Not initializing empty List<int>() for nodes with no outgoing edges
- Assuming all edge targets are automatically graph keys
Solution
Step 1: Understand cycle detection in DFS
Use a recursion stack set to mark nodes currently in the DFS path. If a node is revisited while in this set, a cycle exists.Step 2: Explain why other options fail
Counting visited nodes doesn't detect cycles. BFS alone doesn't detect cycles in directed graphs. Sorting by degree doesn't help detect cycles.Final Answer:
Use an additional recursion stack set to track nodes in the current DFS path and detect back edges -> Option AQuick Check:
Recursion stack detects cycles in DFS [OK]
- Ignoring recursion stack for cycle detection
- Assuming BFS detects cycles in directed graphs
- Using node count to detect cycles
Ready to prove it?
Pass the test and this pattern moves unknown
