PythonStudio
Interview Problems

Course Schedule

medium · graph

There are `num_courses` courses, labeled 0 through num_courses - 1. You are given a list `prerequisites`, where each pair [course, prerequisite] means you must take `prerequisite` before `course`. Decide whether it is possible to finish every course, or whether the prerequisites contain a cycle that makes it impossible. Input: `num_courses` (an integer) and `prerequisites` (a list of [course, prerequisite] pairs). Output: True if all courses can be finished, otherwise False. Example: num_courses = 2, prerequisites = [[1, 0]] -> True, because course 0 can be taken first and then course 1. Example: num_courses = 2, prerequisites = [[1, 0], [0, 1]] -> False, because the two courses depend on each other.

Starter code

def can_finish(num_courses: int, prerequisites: list[list[int]]) -> bool:
    """Return True if all courses can be finished, else False."""
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python compiler