Back to articles
Course Schedule: Master Topological Sort with Kahn's Algorithm

Course Schedule: Master Topological Sort with Kahn's Algorithm

via Dev.toPartners DSA

Have you ever looked at a university course catalog and realized you can't take "Advanced Algorithms" without finishing "Data Structures" first? In computer science, this is a Dependency Management problem. In LeetCode terms, this is the Course Schedule problem, and it's the perfect way to learn about Topological Sorting in Directed Acyclic Graphs (DAGs). The Problem Given numCourses and a list of prerequisites (where [a, b] means you must take course b before course a ), can you finish all courses? Basically, we need to check if the graph contains a cycle . If there is a cycle (e.g., A needs B, B needs C, and C needs A), it’s impossible to finish. The Strategy: Kahn’s Algorithm (BFS) Kahn’s Algorithm works by looking at the indegree of each node. The indegree is simply the number of incoming edges (dependencies) a node has. Build an Adjacency List: Represent the courses and their dependencies. Calculate Indegrees: Count how many prerequisites each course has. Queue the "Free" Courses:

Continue reading on Dev.to

Opens in a new tab

Read Full Article
2 views

Related Articles