VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-course-schedule/

⇱ CSES Solutions – Course Schedule - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions – Course Schedule

Last Updated : 23 Jul, 2025

You have to complete n courses. There are m requirements of form "course a has to be completed before course b". Your task is to find an order in which you can complete the courses.

Examples:

Input: n = 5, m = 3, requirements[][] = {{1, 2}, {3, 1}, {4, 5}}
Output: 3 4 1 5 2
Explanation:

  • Since course 3 and 4 have no requirements, we can complete course 3 and 4.
  • After completing course 3, we can complete course 1.
  • After completing course 4, we can complete course 5.
  • After completing course 1, we can complete course 2.

Input: n = 4, m = 2, requirements[][] = {{4, 2}, {3, 1}}
Output: 3 4 1 2
Explanation:

  • Since course 3 and 4 have on requirements, we can complete course 3 and 4.
  • After completing course 3, we can complete course 1.
  • After completing course 4, we can complete course 2.

Approach: To solve the problem, follow the below idea:

The problem can be solved using Topological Sort. Each course can be considered as a node and each requirement (a, b) can be considered as a directed edge from node a to node b. Now, we can find the topological sort of the graph to find the order in which courses can be completed.

Step-by-step approach:

  • Construct a graph of N nodes for N courses.
  • For every requirement, draw directed edges between the nodes and keep track of the indegree of each node.
  • Maintain a queue to keep track of nodes which we can visit next.
  • Push all the nodes with indegree 0 into the queue.
  • Till queue is not empty,
    • Pop the node at the front of the queue and push it into the ans vector.
    • Decrease the indegree of all the neighboring nodes by 1.
    • If the indegree of neighboring node becomes 0, push the neighboring node to the queue.
  • After the queue becomes empty, print the ans vector as the final answer.

Below is the implementation of the algorithm:


Output
3 4 1 5 2 

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment
Article Tags:
Article Tags: