Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-100

Course Schedule

Problem

Given num_courses and prerequisite pairs [a, b] meaning course b must be taken before course a, return True if all courses can be finished.

Build the directed graph and indegrees, then repeatedly remove zero-indegree nodes; if fewer than num_courses nodes are removed, a cycle exists. An empty prerequisite list is always feasible.

Hint

If Kahn's algorithm cannot remove every node, the remaining nodes form at least one cycle.

Test cases

case 1
in: [2,[[1,0]]]
expected: true
case 2
in: [2,[[1,0],[0,1]]]
expected: false
case 3
in: [4,[[1,0],[2,0],[3,1],[3,2]]]
expected: true
case 4
in: [3,[]]
expected: true
case 5
in: [1,[]]
expected: true
Starter codePython
def can_finish_courses(num_courses, prerequisites):
    # Your code here
    pass

5 test cases · run your code against them in the editor