Can Every Task Be Scheduled Given Dependency Pairs?
Trees & GraphsAuto-graded · 20 test casesLast updated
Tests modeling dependencies as a directed graph and detecting whether a cycle prevents a complete valid ordering, e.g. via indegree-based topological sorting.
Scheduling With Dependencies
A study plan has n modules, numbered 0 through n - 1. Certain modules depend on others being finished first. These dependencies are given as a list of pairs requirements, where each pair [x, y] means module y must be completed before module x can be started.
Write a function that decides whether it is possible to complete every one of the n modules while respecting all the dependencies. Return True if some order of completing the modules satisfies every pair, and False otherwise.
Notes on behavior:
- A module with no dependencies can be done at any time.
- A pair of the form
[x, x]means a module depends on itself, so it can never be completed. - Modules that do not appear in any pair still count and can always be completed on their own.
- The dependencies may form several unconnected groups; the answer is
Trueonly if all groups can be fully completed.
Constraints
1 <= n <= 20000 <= len(requirements) <= 5000- Each pair
[x, y]satisfies0 <= x, y < n. - All pairs in
requirementsare distinct.
Examples
Example 1
Input: can_complete_all(2, [[1, 0]])
Output: True
Example 2
Input: can_complete_all(2, [[1, 0], [0, 1]])
Output: False
Hints
Hint 1
Treat each module as a node and each pair [x, y] as a directed edge from y to x. The question becomes whether this directed graph contains a cycle.
Hint 2
Count, for every module, how many unfinished dependencies it has (its in-degree). Modules with zero can be completed right now; completing one lowers the count of the modules that depend on it.
Hint 3
Simulate this with a queue and count how many modules you complete. If the count reaches n, everything can be finished; if it falls short, the leftover modules are stuck behind a cycle.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Build a directed graph where each pair [x, y] becomes an edge y -> x (finishing y unlocks progress on x). All modules can be completed exactly when this graph has no directed cycle, because modules on a cycle each wait on another module of the cycle and none can ever start.
To check for a cycle, use Kahn's algorithm (BFS topological sort):
- Compute for each module the number of unmet dependencies (its in-degree), and an adjacency list of the modules each one unlocks.
- Put every module with zero unmet dependencies into a queue.
- Repeatedly remove a module from the queue, count it as completed, and decrease the pending count of each module it unlocks. When a count reaches zero, enqueue that module.
- If the number of completed modules equals
n, returnTrue; otherwise returnFalse.
Why it is correct
- No cycle implies everything is processed. Any acyclic directed graph has at least one node with in-degree zero. Removing it leaves a smaller acyclic graph, which again has such a node, and so on until all nodes are removed.
- A cycle implies some modules are never processed. Take the first module of a cycle that would be dequeued. Its predecessor on the cycle would need to have been processed already, contradicting that it is the first. So cycle modules keep a positive pending count forever, and
done < n.
Self-dependencies [x, x] give module x a pending count of at least 1 that can never drop, so they are handled correctly without special-casing. Isolated modules start with a count of zero and are counted.
Complexity
Let E = len(requirements).
- Time: O(n + E), since each module is enqueued once and each edge is processed once.
- Space: O(n + E) for the adjacency lists, pending counts, and queue.
Reference solution
from collections import deque
from typing import List
def can_complete_all(n: int, requirements: List[List[int]]) -> bool:
unlocks = [[] for _ in range(n)]
pending = [0] * n
for module, dependency in requirements:
unlocks[dependency].append(module)
pending[module] += 1
queue = deque(m for m in range(n) if pending[m] == 0)
done = 0
while queue:
module = queue.popleft()
done += 1
for nxt in unlocks[module]:
pending[nxt] -= 1
if pending[nxt] == 0:
queue.append(nxt)
return done == n