Can Every Module in a Study Plan Be Finished?
Trees & GraphsAuto-graded · 22 test casesLast updated
Decide whether a set of ordering rules between numbered modules contains a circular dependency, by detecting a cycle in a directed graph.
Finishing a Study Plan
A school offers a number of modules, numbered from 0 to module_count - 1. Some modules must be completed before others can be started. These rules are given as pairs [first, then], which means that module first has to be finished before module then can be taken.
A study plan is feasible if there is some order in which every module can be taken so that all the rules are respected. A plan is not feasible when the rules form a loop, for example, module 0 must come before 1, 1 before 2, and 2 before 0. A rule that makes a module depend on itself, such as [3, 3], is also a loop.
Write a function that returns True if all modules can be completed while obeying every rule, and False otherwise.
Input
module_count: the total number of modules, labeled0throughmodule_count - 1.rules: a list of pairs[first, then], each pair holding two module labels.
Output
Return a boolean: True if the plan is feasible, False if it contains a circular dependency.
Notes
- If there are no rules, the plan is feasible.
- The modules may form several unrelated groups. A loop in any one group makes the whole plan infeasible.
Constraints
1 <= module_count <= 20000 <= len(rules) <= 5000- Every pair in
rulesis distinct. - Every label in a pair is between
0andmodule_count - 1.
Examples
Example 1
Input: can_finish_all_modules(2, [[1, 0]])
Output: True
Example 2
Input: can_finish_all_modules(2, [[1, 0], [0, 1]])
Output: False
Hints
Hint 1
Treat each module as a node and each rule [first, then] as a directed edge from first to then. The question becomes whether this directed graph has a cycle.
Hint 2
A module can be taken right away if it has no unmet requirements. Count the incoming edges of every node and start with the ones whose count is zero.
Hint 3
Each time you take a module, lower the count of every module that depends on it, and make any module whose count reaches zero available. If the number of modules you managed to take is less than module_count, a cycle blocked the rest.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Think of each module as a node and each rule [first, then] as a directed edge first -> then. All modules can be completed exactly when this directed graph has no cycle.
We detect cycles with a topological-sort procedure (Kahn's algorithm):
- Build, for every module, the list of modules that depend on it, and count how many unmet prerequisites each module has (its in-degree).
- Put every module with zero unmet prerequisites into a queue. These can be taken immediately.
- Repeatedly remove a module from the queue and count it as taken. For each module that depends on it, reduce its unmet count by one. If that count reaches zero, add it to the queue.
- When the queue is empty, the plan is feasible exactly when the number of taken modules equals
module_count.
Why it is correct
- No cycle: A non-empty acyclic graph always has a node with no incoming edges. After removing taken modules and their outgoing edges, the rest is still acyclic, so another such node exists. The queue therefore never empties before all modules are taken.
- Cycle present: Consider any module on a cycle. Its predecessor on the cycle must be taken before its count can reach zero, and that predecessor needs its own predecessor, and so on around the loop. None of them can go first, so none is ever queued, and the final count is below
module_count.
Self-dependencies such as [3, 3] are handled naturally: module 3 always has an unmet prerequisite that only it could satisfy, so it is never taken. Separate groups are handled because every zero-requirement module from every group starts in the queue, while a cycle in any group leaves its modules untaken.
Complexity
With V = module_count and E = len(rules):
- Time: O(V + E), since building the structures costs O(V + E) and each node and edge is processed once.
- Space: O(V + E) for the adjacency lists, counts and queue.
Reference solution
from collections import deque
from typing import List
def can_finish_all_modules(module_count: int, rules: List[List[int]]) -> bool:
followers = [[] for _ in range(module_count)]
unmet = [0] * module_count
for first, then in rules:
followers[first].append(then)
unmet[then] += 1
available = deque(i for i, d in enumerate(unmet) if d == 0)
taken = 0
while available:
current = available.popleft()
taken += 1
for nxt in followers[current]:
unmet[nxt] -= 1
if unmet[nxt] == 0:
available.append(nxt)
return taken == module_count