VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-whether-it-is-possible-to-finish-all-tasks-or-not-from-given-dependencies/

⇱ Course Schedule I - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Course Schedule I

Last Updated : 24 Mar, 2026

Given n courses labeled from 0 to n - 1, and an array prerequisites[][] where prerequisites[i] = [x, y] indicates that you must take course y before taking course x.
Return true if it is possible to complete all courses, otherwise return false.

Examples:

Input: n = 4, prerequisites[][] = [[2, 0], [2, 1], [3, 2]]
Output: true
Explanation: To take course 2, you must first finish courses 0 and 1.
To take course 3, you must first finish course 2.
All courses can be completed, for example in the order [0, 1, 2, 3] or [1, 0, 2, 3].

Input: n = 3, prerequisites[][] = [[0, 1], [1, 2], [2, 0]]
Output: false
Explanation: To take course 0, you must first finish course 1.
To take course 1, you must first finish course 2.
To take course 2, you must first finish course 0.
Since each course depends on the other, it is impossible to complete all courses.

[Approach 1] - Using DFS for Cycle Detection

The idea is to represent the courses and their prerequisites as a directed graph, where each course is a vertex. For each prerequisite [x, y], since course y must be completed before course x, we add a directed edge from y to x. If the graph contains a cycle, it means some courses depend on each other in a loop, making it impossible to complete all courses. If there is no cycle, a valid order exists to finish all courses.

For more details, refer to Cycle Detection using DFS in Directed Graph.


Output
true

Time Complexity: O(V+E), where V is the number of vertices and E is the number of edges.
Auxiliary Space: O(V+E)

[Approach 2] - Using Topological Sorting

The idea is to represent the courses and their prerequisites as a directed graph, where each course is a vertex. For each prerequisite [x, y], since course y must be completed before course x, we add a directed edge from y to x. By performing a topological sort, we can determine whether it is possible to complete all courses. If all courses are visited, there is no cycle and all courses can be completed. If any course remains unvisited, it means there is a cycle, where courses depend on each other in a loop, making it impossible to finish all of them.


Output
true

Time Complexity: O(V+E), where V is the number of vertices and E is the number of edges.
Auxiliary Space: O(V)

Comment