Course Schedule

Free with account Updated Nov 19, 2026 · 5 min read
On this page

    Problem statement

    There are n courses labelled 0 to n − 1 and a list of prerequisite pairs [a, b], meaning you must take b before a. Return true if it is possible to finish every course.

    Behind the story is a directed graph, and the question is whether it has a cycle. It's the gateway to topological sorting, which also schedules build steps, package installs and task pipelines. Original problem: LeetCode 207.

    Example

    On the left, course 0 unlocks 1 and 2, which both unlock 3, so every course can be taken; on the right, 0, 1 and 2 wait on each other in a cycle.
    On the left, course 0 unlocks 1 and 2, which both unlock 3, so every course can be taken; on the right, 0, 1 and 2 wait on each other in a cycle.
    Input:  n = 4, prerequisites = [[1,0], [2,0], [3,1], [3,2]]
    Output: true     # e.g. 0, 1, 2, 3
    Input:  n = 3, prerequisites = [[1,0], [2,1], [0,2]]
    Output: false    # 0 -> 1 -> 2 -> 0

    Constraints (assumed)

    • 1 ≤ n ≤ 2,000; up to 5,000 pairs.
    • Pairs may repeat; a course may have no prerequisites.

    What this question tests

    • Turning a word problem into a directed graph.
    • Cycle detection in a directed graph, via Kahn's algorithm or DFS colouring.
    • Getting the edge direction right.

    Questions to ask first

    1. Which way does [a, b] point? (Here: b must come before a, so the edge is b → a.)
    2. Can a course list itself as a prerequisite? That's a cycle of length 1; the algorithm handles it.
    3. Do you need an order, or just yes/no? (Here: yes/no; returning the order is Course Schedule II.)
    4. Can pairs repeat? Duplicates just add duplicate edges and in-degree; still correct.