Determine whether all courses can be finished given prerequisite constraints.
Course Schedule
You are given courses labeled from $0n - 1$ and a list of prerequisite pairs. Each pair indicates that one course must be completed before another course can be taken.
Return true if it is possible to finish every course. Otherwise, return false.
The prerequisite relationships form a directed graph. Your task is to determine whether that graph contains a cycle.
Input Format
- An integer
n, the number of courses. - A list of pairs
prerequisites, where each pair[a, b]means coursebmust be taken before coursea.
Output Format
- Return a boolean value:
trueif all courses can be completed.falseif the prerequisite graph has a cycle.
Constraints
prerequisites[i]contains exactly two integers.- Each course index is in the range
[0, n - 1]. - A course may appear in multiple prerequisite relations.
Hints
- Think of each prerequisite as a directed edge.
- If there is a directed cycle, no valid course order exists.
- You can solve this with either topological sorting or DFS-based cycle detection.
Example 1
Input
n = 2, prerequisites = [[1,0]]
Output
true
Explanation
Course 0 can be taken first, then course 1.
Example 2
Input
n = 2, prerequisites = [[1,0],[0,1]]
Output
false
Explanation
The two courses depend on each other, so a cycle exists.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.