23. Course Schedule
The problem can be found at the following link: Question Link
My Approach
I am using a topological sorting approach to find the order of courses. The idea is to first create a directed graph representing the prerequisite relationships between courses. Then, I calculate the in-degree (number of incoming edges) for each course. Starting with the courses that have no prerequisites (in-degre e = 0), I use a queue to perform a topological sort.
Creating the Graph
I create an array of vectors to represent the graph, where
graph[i]
contains the courses that depend on coursei
.I also maintain an array
degree
to store the in-degree of each course.
Topological Sort
I initialize a queue with courses having no prerequisites (in-degree = 0).
While the queue is not empty, I dequeue a course, add it to the result, and reduce the in-degree of its dependent courses.
If any dependent course now has in-degree = 0, I enqueue it.
Validating the Result
After the topological sort, I check if all courses have been included in the result. If not, it means there is a cycle, and the schedule is not possible.
Time and Auxiliary Space Complexity
Time Complexity:
O(n + m)
, where n is the number of courses and m is the number of prerequisites. Building the graph takes O(m) time, and the topological sort takes O(n + m) time.Auxiliary Space Complexity:
O(n)
, where n is the number of courses. This is used for the degree array and the queue.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated