Topological Sort Using DFS in DSA Javascript - 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.
function topologicalSort(graph) {
const visited = new Set();
const stack = [];
function dfs(node) {
visited.add(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) dfs(neighbor);
}
stack.push(node);
}
for (const node in graph) {
if (!visited.has(node)) dfs(node);
}
return stack.reverse();
}
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.
- How many times: Each node is visited once, and each edge is checked once during DFS.
As the number of nodes and edges increases, the total work grows roughly with the sum of nodes and edges.
| Input Size (n nodes, e edges) | Approx. Operations |
|---|---|
| 10 nodes, 15 edges | About 25 operations (10 + 15) |
| 100 nodes, 200 edges | About 300 operations (100 + 200) |
| 1000 nodes, 5000 edges | About 6000 operations (1000 + 5000) |
Pattern observation: The work grows linearly with the number of nodes plus edges.
Time Complexity: O(n + e)
This means the time needed grows in a straight line with the total number of nodes and edges in the graph.
[X] Wrong: "DFS visits nodes multiple times, so time is O(n * e)."
[OK] Correct: Each node is marked visited and processed only once, so edges are checked only once, not repeatedly.
Understanding this time complexity helps you explain how efficient graph algorithms work and shows you can analyze recursive traversals clearly.
"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 it is processed.Step 2: Relate DFS order to dependencies
In Topological Sort, nodes are added after visiting all their dependencies, so dependencies come before dependents.Final Answer:
To visit nodes in a way that ensures dependencies come before dependents -> Option DQuick Check:
DFS ensures dependency order = A [OK]
- Confusing DFS with BFS for topological sorting
- Thinking DFS finds shortest paths
- Mixing cycle detection with topological order
Solution
Step 1: Understand visited marking in DFS
Visited is usually an array or object where each node's visited status is stored as a boolean.Step 2: Correct syntax for marking visited
Assigning true to visited[node] marks that node visited; using '==' is comparison, not assignment.Final Answer:
visited[node] = true; -> Option CQuick Check:
Assign true to visited[node] = A [OK]
- Using '==' instead of '=' for assignment
- Using push on visited array instead of index assignment
- Overwriting visited variable instead of marking node
const graph = {
5: [2, 0],
4: [0, 1],
2: [3],
3: [1],
0: [],
1: []
};
const visited = {};
const stack = [];
function dfs(node) {
visited[node] = true;
for (const neighbor of graph[node]) {
if (!visited[neighbor]) dfs(neighbor);
}
stack.push(node);
}
for (const node in graph) {
if (!visited[node]) dfs(node);
}
console.log(stack.reverse());Solution
Step 1: Perform DFS and track stack push order
DFS visits nodes deeply, pushing nodes after visiting neighbors. For node 5: visits 2, then 3, then 1, then 0; for node 4: visits 0 and 1. Stack push order is [1,3,2,0,5,4] reversed to [4,5,0,2,3,1].Step 2: Reverse stack to get topological order
Reversing stack gives [4, 5, 0, 2, 3, 1], which respects dependencies.Final Answer:
[4, 5, 0, 2, 3, 1] -> Option BQuick Check:
DFS post-order reversed = [4,5,0,2,3,1] [OK]
- Not reversing the stack before output
- Visiting nodes in wrong order due to object key iteration
- Confusing push order with final topological order
function dfs(node, graph, visited, stack) {
if (visited[node]) return;
visited[node] = true;
for (const neighbor of graph[node]) {
dfs(neighbor, graph, visited, stack);
}
stack.push(node);
}
const graph = {0: [1], 1: [2], 2: []};
const visited = {};
const stack = [];
for (const node in graph) {
dfs(node, graph, visited, stack);
}
console.log(stack.reverse());Solution
Step 1: Analyze visited check and recursion
The code checks if node is visited before recursion, preventing repeated visits.Step 2: Confirm stack usage and output
Nodes are pushed after visiting neighbors, and stack is reversed for correct order.Final Answer:
No bug; code works correctly -> Option AQuick Check:
No bug; code works correctly = C [OK]
- Calling dfs without visited check causing infinite recursion
- Not reversing stack before output
- Resetting visited inside DFS causing wrong results
Solution
Step 1: Understand cycle detection in DFS
Cycle exists if a node is visited again in the current DFS path (back edge).Step 2: Use recursion stack to track current path
Maintain a recursion stack array marking nodes currently in DFS call; if a neighbor is in recursion stack, cycle detected.Final Answer:
Use an extra recursion stack to track nodes in the current DFS path and detect back edges -> Option AQuick Check:
Recursion stack detects cycles = D [OK]
- Only using visited array without recursion stack
- Trying to detect cycles by node count mismatch
- Using BFS without proper cycle detection logic
Ready to prove it?
Pass the test and this pattern moves unknown
