Smallest Job Schedule Under Dependency Rules
Trees & GraphsAuto-graded · 21 test casesLast updated
Produce the lexicographically smallest topological ordering of a dependency graph, or an empty list if the dependencies contain a cycle.
Smallest Job Schedule Under Dependency Rules
A build system has n jobs numbered 0 to n - 1. You are given a list of rules, where each rule is a pair [a, b] meaning job a must finish before job b can start.
Return a schedule that runs every job exactly once and respects every rule.
- If several schedules are valid, return the lexicographically smallest one. Compare two schedules position by position, and the first position where they differ decides: the schedule with the smaller job number there is smaller.
- If no valid schedule exists because the rules form a cycle, return an empty list
[].
Notes
- Jobs that appear in no rule must still be included in the schedule.
- A rule such as
[a, a]is a cycle, so the answer is[]. - The same rule may appear more than once. Duplicates do not change the answer.
- If
n = 0, return[].
Constraints
0 <= n <= 10^50 <= len(dependencies) <= 10^5- Each rule is a pair
[a, b]with0 <= a, b < n. - The return value is a list of
ndistinct integers, or[]if no valid schedule exists.
Examples
Example 1
Input: schedule_jobs(4, [[0, 1], [0, 2], [1, 3], [2, 3]])
Output: [0, 1, 2, 3]
Example 2
Input: schedule_jobs(2, [[0, 1], [1, 0]])
Output: []
Example 3
Input: schedule_jobs(3, [])
Output: [0, 1, 2]
Hints
Hint 1
Think of each rule as a directed edge a -> b. A job can run once all of its prerequisites are done, so track how many unfinished prerequisites each job has.
Hint 2
Start with the jobs that have zero unfinished prerequisites. Whenever you finish a job, reduce the count for each job that depends on it, and any job whose count reaches zero becomes available.
Hint 3
To get the lexicographically smallest result, always pick the smallest available job, which a min-heap does efficiently. If you end up scheduling fewer than n jobs, a cycle exists, so return an empty list.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each rule [a, b] as a directed edge a -> b. A valid schedule is a topological order of this graph, and one exists exactly when the graph has no cycle.
We use Kahn's algorithm with a min-heap instead of a plain queue:
- Build an adjacency list and count each job's in-degree, which is the number of rules that require something to finish before it.
- Put every job with in-degree 0 into a min-heap. These are the jobs that can run right now.
- Repeatedly pop the smallest job from the heap and append it to the schedule. For each job that depends on it, decrement that job's in-degree. If the in-degree reaches 0, push it onto the heap.
- If the schedule contains all
njobs, return it. Otherwise some jobs are stuck on a cycle, so return[].
Why it is correct
- Validity: A job enters the heap only when all its prerequisites have already been output, so every rule points forward in the result.
- Cycle detection: No job on a cycle can reach in-degree 0, because it waits on another job from the same cycle. The output then has fewer than
njobs. Conversely, in an acyclic graph there is always at least one job with no remaining prerequisites, so the process never stalls early. - Lexicographic minimality: At each step the heap holds exactly the jobs that may legally go next. Choosing the smallest one makes the current position as small as possible. Finishing a job can only add options and never removes any, so this choice never hurts later positions. Any schedule that puts a larger job at the first differing position is lexicographically larger.
- Edge cases: Isolated jobs start with in-degree 0 and are included. Self-loops keep in-degree above 0 forever, giving
[]. Duplicate rules increment and decrement the in-degree the same number of times. Withn = 0the result is the empty list.
Complexity
- Time:
O((n + m) log n), wheremis the number of rules. Each job is pushed and popped once, and each rule is processed once. - Space:
O(n + m)for the graph, in-degrees, and heap.
Reference solution
import heapq
from typing import List
def schedule_jobs(n: int, dependencies: List[List[int]]) -> List[int]:
graph = [[] for _ in range(n)]
indegree = [0] * n
for a, b in dependencies:
graph[a].append(b)
indegree[b] += 1
ready = [job for job in range(n) if indegree[job] == 0]
heapq.heapify(ready)
order = []
while ready:
job = heapq.heappop(ready)
order.append(job)
for nxt in graph[job]:
indegree[nxt] -= 1
if indegree[nxt] == 0:
heapq.heappush(ready, nxt)
return order if len(order) == n else []