Course Schedule
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

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
- Which way does [a, b] point? (Here: b must come before a, so the edge is b → a.)
- Can a course list itself as a prerequisite? That's a cycle of length 1; the algorithm handles it.
- Do you need an order, or just yes/no? (Here: yes/no; returning the order is Course Schedule II.)
- Can pairs repeat? Duplicates just add duplicate edges and in-degree; still correct.
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.