MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Cycle Detection & Topological Sorting (Kahn's BFS & DFS)0%
Study Materials
Data Structures & AlgorithmsProgress 0%
1.1Introduction to DSA, Big-O, Big-Omega & Big-Theta Notations1.2Time Complexity Calculation Rules & Common Runtime Patterns1.3Space Complexity, Auxiliary Memory & Stack vs Heap Allocation
8.1Graph Theory: Adjacency Matrix vs List & BFS vs DFS Traversals8.2Cycle Detection & Topological Sorting (Kahn's BFS & DFS)8.3Shortest Paths: Dijkstra's Algorithm with Min-Heap & BFS for Unweighted8.4Dynamic Programming: Overlapping Subproblems, Memoization vs Tabulation8.5Classic DP Master Patterns: 0/1 Knapsack, Coin Change & LCS
HomeTutorialsData Structures & AlgorithmsCycle Detection & Topological Sorting (Kahn's BFS & DFS)
Shortest Paths: Dijkstra's Algorithm with Min-Heap & BFS for Unweighted

Cycle Detection & Topological Sorting (Kahn's BFS & DFS)

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

In graph theory, detecting cycles and ordering dependencies are two fundamental problems encountered across build systems (Make/Gradle/Webpack), package managers (npm, pip), university course prerequisites, and relational database foreign key constraints.


1. What is Topological Sorting?

A Topological Sort of a Directed Acyclic Graph (DAG) is a linear ordering of its vertices such that for every directed edge $(u \to v)$, vertex $u$ comes before vertex $v$ in the sequence.

1Course Prerequisite Graph:
2 [Intro to CS (0)] -----> [Data Structures (1)] -----> [Algorithms (3)]
3 | ^
4 v |
5 [Discrete Math (2)] ---------------------------------------+
6 
7Valid Topological Orders:
8- [0, 1, 2, 3]
9- [0, 2, 1, 3]
Fundamental Theorem: A directed graph has a valid topological sort if and only if it is a DAG (Directed Acyclic Graph). If the graph contains a cycle (e.g., $A \to B \to C \to A$), no topological order can exist because no task in the cycle can be executed first!

2. Cycle Detection Strategies

In Undirected Graphs

  1. 1
    DFS with Parent Tracking: During traversal, if a neighbor has already been visited and is NOT the immediate parent of the current node, an alternative path exists, proving a cycle!
  2. 2
    Disjoint Set Union (Union-Find): For each edge $(u, v)$, if $\text{Find}(u) == \text{Find}(v)$, both nodes already belong to the same connected component; adding edge $(u, v)$ creates a cycle.

In Directed Graphs

Cycles in directed graphs require directional tracking:

  1. 1
    3-Color DFS:
  • White (0): Unvisited node.
  • Gray (1): Currently in the active recursion call stack (being explored).
  • Black (2): Fully processed and all descendants explored.
  • Cycle Condition: If DFS encounters an edge pointing to a Gray node, a Back Edge is found, confirming a directed cycle!
  1. 1
    Kahn's Algorithm (BFS In-Degree): If the final topological sort output contains fewer than $V$ vertices, an unresolved cycle prevented some nodes from ever reaching an in-degree of 0.

3. Kahn's Algorithm Step-by-Step

Kahn's algorithm uses vertex In-Degrees (number of incoming arrows) with a FIFO queue:

1Algorithm Kahn:
21. Compute in-degree for all V vertices.
32. Push all vertices with in-degree == 0 into queue (they have 0 dependencies).
43. While queue is not empty:
5 u = queue.pop()
6 append u to topological_order
7 for each neighbor v of u:
8 in_degree[v] -= 1
9 if in_degree[v] == 0:
10 queue.append(v)
114. If len(topological_order) == V: return topological_order
12 Else: Graph contains a cycle (Deadlock)!

Trace Table for Kahn's Algorithm

Given $V = 4$, Edges: $0 \to 1, 0 \to 2, 1 \to 3, 2 \to 3$:

StepQueue (In-Degree 0)Processed NodeEdge RemovedUpdated In-Degrees [0, 1, 2, 3]Result Array
Init[0]--[0, 1, 1, 2][]
1[]0$0 \to 1, 0 \to 2$[0, 0, 0, 2] (1 and 2 hit 0!)[0]
2[1, 2]1$1 \to 3$[0, 0, 0, 1][0, 1]
3[2]2$2 \to 3$[0, 0, 0, 0] (3 hits 0!)[0, 1, 2]
4[3]3None[0, 0, 0, 0][0, 1, 2, 3]

All 4 nodes processed $\implies$ Valid DAG order: [0, 1, 2, 3].


4. Dual-Language Implementation

Python 3: Kahn's Algorithm & DFS 3-Coloring

1from collections import deque, defaultdict
2from typing import List, Optional, Dict
3 
4class DirectedGraph:
5 def __init__(self, num_nodes: int):
6 self.num_nodes = num_nodes
7 self.adj: Dict[int, List[int]] = defaultdict(list)
8 self.in_degree: List[int] = [0] * num_nodes
9 
10 def add_edge(self, u: int, v: int) -> None:
11 # Add directed edge u -> v (u precedes v)
12 self.adj[u].append(v)
13 self.in_degree[v] += 1
14 
15 def kahns_topological_sort(self) -> Optional[List[int]]:
16 # Kahn's BFS Algorithm: Returns topological ordering, or None if a cycle is detected
17 queue = deque([i for i in range(self.num_nodes) if self.in_degree[i] == 0])
18 topo_order: List[int] = []
19 
20 while queue:
21 node = queue.popleft()
22 topo_order.append(node)
23 
24 for neighbor in self.adj[node]:
25 self.in_degree[neighbor] -= 1
26 if self.in_degree[neighbor] == 0:
27 queue.append(neighbor)
28 
29 # If topo_order contains all vertices, no cycle exists
30 if len(topo_order) == self.num_nodes:
31 return topo_order
32 return None # Cycle detected!
33 
34 def has_cycle_dfs(self) -> bool:
35 # 3-Color DFS Cycle Detection:
36 # 0: White (Unvisited), 1: Gray (Visiting/Active Stack), 2: Black (Done)
37 color = [0] * self.num_nodes
38 
39 def dfs(u: int) -> bool:
40 color[u] = 1 # Mark Gray (entering call stack)
41 for v in self.adj[u]:
42 if color[v] == 1:
43 return True # Found back-edge to active ancestor!
44 if color[v] == 0:
45 if dfs(v):
46 return True
47 color[u] = 2 # Mark Black (exiting call stack)
48 return False
49 
50 for node in range(self.num_nodes):
51 if color[node] == 0:
52 if dfs(node):
53 return True
54 return False
55 
56# Example Execution
57if __name__ == "__main__":
58 dag = DirectedGraph(4)
59 dag.add_edge(0, 1)
60 dag.add_edge(0, 2)
61 dag.add_edge(1, 3)
62 dag.add_edge(2, 3)
63 
64 print("Kahn's Topo Sort:", dag.kahns_topological_sort()) # [0, 1, 2, 3]
65 print("Has Cycle?:", dag.has_cycle_dfs()) # False

Modern JavaScript (Node.js) Implementation

1class DirectedGraph {
2 constructor(numNodes) {
3 this.numNodes = numNodes;
4 this.adj = new Map();
5 this.inDegree = new Array(numNodes).fill(0);
6 for (let i = 0; i < numNodes; i++) {
7 this.adj.set(i, []);
8 }
9 }
10 
11 addEdge(u, v) {
12 this.adj.get(u).push(v);
13 this.inDegree[v]++;
14 }
15 
16 kahnsTopologicalSort() {
17 const queue = [];
18 for (let i = 0; i < this.numNodes; i++) {
19 if (this.inDegree[i] === 0) queue.push(i);
20 }
21 
22 const topoOrder = [];
23 let head = 0; // O(1) dequeue pointer
24 
25 while (head < queue.length) {
26 const u = queue[head++];
27 topoOrder.push(u);
28 
29 const neighbors = this.adj.get(u) || [];
30 for (const v of neighbors) {
31 this.inDegree[v]--;
32 if (this.inDegree[v] === 0) {
33 queue.push(v);
34 }
35 }
36 }
37 
38 return topoOrder.length === this.numNodes ? topoOrder : null;
39 }
40}
41 
42// Example Execution
43const g = new DirectedGraph(4);
44g.addEdge(0, 1);
45g.addEdge(0, 2);
46g.addEdge(1, 3);
47g.addEdge(2, 3);
48 
49console.log("Kahn's Ordering:", g.kahnsTopologicalSort()); // [0, 1, 2, 3]

5. Complexity Analysis

AlgorithmTime ComplexitySpace ComplexityBest Feature
Kahn's Algorithm (BFS)$O(V + E)$$O(V)$Simultaneously outputs valid ordering AND detects cycles
DFS 3-Coloring$O(V + E)$$O(V)$Intuitive recursive cycle verification via back-edges
Undirected Union-Find$O(E \cdot \alpha(V))$$O(V)$Ultra-fast dynamic cycle detection in undirected graphs

6. Real-World Applications & Edge Cases

  1. 1
    Course Schedule (LeetCode 207 / 210): Direct mapping to Kahn's algorithm or 3-color DFS.
  2. 2
    Build Systems (Webpack, Make, Vite): Compilers parse import statements into a DAG. Circular imports (e.g., Module A imports Module B which imports Module A) trigger build cycle errors.
  3. 3
    Spreadsheet Formula Calculation: Cells with dependent formulas (e.g., A1 = B1 + C1) require topological evaluation. Circular references (A1 = B1 + 1 and B1 = A1 + 1) are flagged as illegal cycles.

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
Which type of graph can produce at least one valid topological sort?
Question 2
In Kahn's Algorithm, which vertices are initially inserted into the queue?
Question 3
In the 3-color DFS cycle detection algorithm for directed graphs, what does encountering a node marked "Gray" (visiting) signify?
Question 4
What is the time complexity of Kahn's topological sort on a graph with $V$ vertices and $E$ edges?
Question 5
If Kahn's algorithm terminates and the length of the topological order array is less than the total number of vertices $V$, what does this prove?

Next Lesson

Shortest Paths: Dijkstra's Algorithm with Min-Heap & BFS for Unweighted

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Graph Theory: Adjacency Matrix vs List & BFS vs DFS TraversalsShortest Paths: Dijkstra's Algorithm with Min-Heap & BFS for Unweighted

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Data Structures & Algorithms with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext