Alphabetical Job Scheduler with Prerequisite Rules
Trees & GraphsAuto-graded · 18 test casesLast updated
Produce a full run order for jobs under prerequisite constraints, always picking the alphabetically smallest available job, or return an empty list if a cycle exists.
Alphabetical Job Scheduler
A scheduler needs to run a collection of jobs. Each job has a unique name, and some jobs may only start after others have finished.
You are given:
jobs: a list of distinct job names.requirements: a list of pairs[before, after]. Each pair means the jobbeforemust run earlier than the jobafter.
Build a single run order that contains every job and satisfies these rules:
- Each job appears in the order exactly once.
- For every pair
[before, after],beforeappears at an earlier position thanafter. - At each step, consider all jobs whose prerequisites have already been scheduled. Among those, choose the one whose name is smallest in standard lexicographic (dictionary) order.
- Jobs that are not mentioned in any pair are still scheduled, following the same selection rule as everything else.
If the requirements contain a cycle, so that no order can satisfy rule 2 for all jobs, return an empty list []. Do not return a partial order. A cycle in any part of the graph makes the whole result empty.
Constraints
1 <= len(jobs) <= 20,0000 <= len(requirements) <= 50,000- Each job name has between 1 and 20 lowercase English letters.
- All names in
jobsare distinct. - In each pair
[a, b], bothaandbappear injobs, anda != b. - The same pair may appear more than once in
requirements. - The order of names in
jobscarries no meaning for the result.
Examples
Example 1
Input: schedule_jobs(['build', 'test', 'lint', 'deploy'], [['lint', 'test'], ['build', 'test'], ['test', 'deploy']])
Output: ['build', 'lint', 'test', 'deploy']
Example 2
Input: schedule_jobs(['zeta', 'alpha', 'beta'], [])
Output: ['alpha', 'beta', 'zeta']
Hints
Hint 1
Count, for each job, how many prerequisite pairs point at it. Jobs with a count of zero are the ones that can run right now.
Hint 2
You need to repeatedly extract the smallest name from the set of currently runnable jobs. Which data structure supports that efficiently while new jobs keep becoming runnable?
Hint 3
After scheduling a job, lower the count of each job that depends on it. Duplicate pairs raise the count multiple times and lower it multiple times, so they stay consistent. If you end up with fewer scheduled jobs than total jobs, a cycle blocked some of them.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a topological sort with a deterministic tie-break, so Kahn's algorithm with a min-heap fits well.
- For every job, keep a list of the jobs that depend on it (
followers) and a counter of its unfinished prerequisites (pending). Each pair[before, after]appendsaftertofollowers[before]and incrementspending[after]. - Put every job with
pending == 0into a min-heap. This includes jobs that appear in no pair. - Repeatedly pop the smallest name from the heap and append it to the result. For each of its followers, decrement the counter; when it reaches zero, push that follower onto the heap.
- If the result holds every job, return it. Otherwise return
[], because a cycle prevented some jobs from ever becoming runnable.
Why it is correct
- Ordering constraints: A job enters the heap only after its counter reaches zero, meaning all its prerequisites were already popped and placed earlier in the result.
- Exactly once: A counter only decreases, so it reaches zero at most once. Each job is therefore pushed and popped at most once.
- Tie-breaking: The heap contains exactly the currently runnable jobs, and
heappopreturns the lexicographically smallest, which is rule 3 applied at every step. - Cycles: Every job on a cycle has a prerequisite on that cycle that can never be scheduled first, so none of them reaches zero, and jobs downstream are blocked too. Hence the result is shorter than
jobsexactly when a cycle exists. - Duplicate pairs: A repeated pair increments the counter twice and the decrement loop runs twice, so counts remain consistent without deduplication.
Complexity
- Time: O((V + E) log V), with V jobs and E pairs. Each job is pushed and popped once, and each pair is processed once. Name comparisons cost at most 20 characters.
- Space: O(V + E) for the follower lists, counters, heap, and result.
Reference solution
import heapq
from typing import List
def schedule_jobs(jobs: List[str], requirements: List[List[str]]) -> List[str]:
followers = {job: [] for job in jobs}
pending = {job: 0 for job in jobs}
for before, after in requirements:
followers[before].append(after)
pending[after] += 1
runnable = [job for job in jobs if pending[job] == 0]
heapq.heapify(runnable)
order = []
while runnable:
job = heapq.heappop(runnable)
order.append(job)
for nxt in followers[job]:
pending[nxt] -= 1
if pending[nxt] == 0:
heapq.heappush(runnable, nxt)
return order if len(order) == len(jobs) else []