Detect a Cycle in a Directed Course Prerequisite Graph
Trees & GraphsAuto-graded · 20 test casesLast updated
Tests whether you can model dependency constraints as a directed graph and use topological sort to detect cycles that make all tasks impossible to complete.
Problem
You are managing a collection of n jobs numbered 0 through n - 1. Some jobs have ordering requirements: a job cannot begin until another specific job has already been completed.
You are given an integer n and a list requirements, where each entry [a, b] means job a cannot start until job b is done.
Determine whether it is possible to complete every job. Return True if all jobs can be finished, or False if the constraints make it impossible.
Constraints
1 <= n <= 20000 <= len(requirements) <= 5000requirements[i].length == 20 <= requirements[i][0], requirements[i][1] < n- A job may appear in multiple requirement pairs.
requirements[i][0] != requirements[i][1]is not guaranteed (self-dependencies are possible).
Examples
Example 1
Input: can_finish(2, [[1, 0]])
Output: True
Example 2
Input: can_finish(2, [[1, 0], [0, 1]])
Output: False
Hints
Hint 1
Model the jobs as nodes in a directed graph where an edge from B to A means B must be done before A. The question reduces to: does this graph contain a cycle?
Hint 2
Use Kahn's algorithm: count how many unsatisfied prerequisites each job has (its in-degree). Jobs with in-degree 0 are ready to run immediately. Each time you complete a ready job, reduce the in-degree of every job that depended on it.
Hint 3
If the number of jobs you successfully process equals n, all jobs can be finished. If you get stuck before processing every job, a cycle exists and it is impossible.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Modeling the problem
Each job is a node. For every requirement [a, b], draw a directed edge from b to a, meaning b must come before a. Completing all jobs is possible if and only if this directed graph contains no cycle. A cycle means a group of jobs each waiting on another member of the same group — none of them can ever start.
Kahn's algorithm (topological sort by in-degree)
- Build an adjacency list and compute the in-degree of every node (the number of prerequisites it still needs).
- Seed a queue with every job whose in-degree is
0— these have no unsatisfied dependencies and can run immediately. - Repeatedly dequeue a job, count it as completed, and decrement the in-degree of every job that listed it as a prerequisite. Whenever a dependent's in-degree reaches
0, add it to the queue. - Return
completed == n.
Why this is correct
A job enters the queue only after every one of its prerequisites has been processed, so each dequeued job genuinely can run at that point.
If a cycle exists, every node inside it is waiting for another cycle member. None of them ever reaches in-degree 0, so they are never enqueued, and completed falls short of n.
If no cycle exists, some node always has in-degree 0. Processing it leaves a smaller acyclic graph, and the argument repeats until every job is handled. Isolated jobs (no edges at all) start at in-degree 0 and are picked up immediately in the initial queue.
Edge cases
- No requirements: every job starts at in-degree
0; the answer isTrue. - Self-loop
[0, 0]: job 0's in-degree is incremented but never decremented to0, so it is never processed —False. - Two-node cycle
[[1,0],[0,1]]: both jobs have in-degree1and neither enters the queue —False. - Duplicate edges: in-degree is incremented for each occurrence and decremented the same number of times, so the result stays correct.
Complexity
- Time: O(V + E), where V = n and E = len(requirements). Each job is enqueued at most once, and each edge is relaxed exactly once.
- Space: O(V + E) for the adjacency list, plus O(V) for in-degrees and the queue.
Full solution
from collections import deque
from typing import List
def can_finish(n: int, requirements: List[List[int]]) -> bool:
graph = [[] for _ in range(n)]
indegree = [0] * n
for a, b in requirements:
graph[b].append(a) # b must finish before a
indegree[a] += 1
queue = deque(i for i in range(n) if indegree[i] == 0)
completed = 0
while queue:
job = queue.popleft()
completed += 1
for dependent in graph[job]:
indegree[dependent] -= 1
if indegree[dependent] == 0:
queue.append(dependent)
return completed == n
Alternative: DFS with three-color marking
Mark every node as unvisited, in-progress, or done. During DFS, if you reach a node currently marked in-progress, you have found a back edge, which means a cycle exists. This also runs in O(V + E) time and O(V) space, but in Python the recursion depth can reach V on a long chain, risking a stack overflow. Kahn's iterative approach avoids that risk entirely.