# Solution: Course Schedule

Let's solve the Course Schedule problem using the Topological Sort pattern.

We'll cover the following

## Statement

There are a total of numCourses courses you have to take. The courses are labeled from 0 to numCourses - 1. You are also given a prerequisites array, where prerequisites[i] = [a[i], b[i]] indicates that you must take course b[i] first if you want to take the course a[i]. For example, the pair $[1, 0]$ indicates that to take course $1$, you have to first take course $0$.

Return TRUE if all of the courses can be finished. Otherwise, return FALSE.

Constraints:

• $1 \leq$ numCourses $\leq 1500$
• $0 \leq$ prerequisites.length $\leq 1000$
• prerequisites[i].length $= 2$
• $0 \leq$ a[i], b[i] $<$ numCourses
• All the pairs prerequisites[i] are unique.

## Solution

Initialize the hash map with the vertices and their children. Weâ€™ll use another hash map to keep track of the number of in-degrees of each vertex. Then weâ€™ll find the source vertex (with $0$ in-degree) and increment the counter. Retrieve the source nodeâ€™s children and add them to the queue. Decrement the in-degrees of the retrieved children. Weâ€™ll check whether the in-degree of the child vertex becomes equal to zero, and weâ€™ll increment the counter. Repeat the process until the queue is empty.

Note: The in-degree is the number of edges coming into a vertex in a directed graph.

The primary purpose of finding a vertex with 0 in-degree is to find a course with a pre-requisite count of 0. When we take a course, say a (that is the pre-requisite of another course, say b), weâ€™ll decrement the in-degree of b by 1, and if the in-degree count becomes 0, we can say that the bâ€™s pre-requisites have been completed.

The slide deck below illustrates the algorithm above, where numCourses = 6:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.