Job Scheduling with Cycle Check and Downstream Rerun Set
Trees & GraphsAuto-graded · 24 test casesLast updated
Topologically sort jobs with cycle detection, then use graph reachability to find all jobs affected by changed ones and list them in valid order.
You manage a build pipeline made of named jobs. Some jobs need other jobs to finish first. You must (1) produce a valid run order for all jobs, and (2) after some jobs are modified, work out which jobs must run again and in what order.
Task
Implement order_jobs_and_reruns(jobs, requires, modified) returning a list of two lists:
full_order: an ordering of every job in which each job appears after all of its prerequisites.rerun_order: an ordering of only the jobs that must rerun, also respecting prerequisites.
Input
jobs: a list of unique, non-empty job names.requires: a list of pairs[job, prerequisite], meaningprerequisitemust finish beforejobstarts. Every name in a pair appears injobs. Duplicate pairs have no additional meaning. A pair wherejob == prerequisiteis a cycle.modified: a list of job names, all present injobs. Names may repeat.
Rules
- A modified job must rerun. So must every job that depends on it directly or indirectly (any job reachable by following "is a prerequisite of" links from a modified job).
- Prerequisites that are not affected are assumed to have already completed successfully and are not rerun.
- If the dependency graph contains a cycle anywhere (even among jobs unrelated to the modified ones), return
[["CYCLE"], []]. The nameCYCLEis never used as a job name. - If
jobsis empty, return[[], []].
Deterministic output
Any valid ordering is logically correct, but to make the output reproducible, build full_order with the following procedure:
- Compute, for each job, the number of entries in
requiresthat list it as the dependent (counting duplicates). - Start a FIFO queue containing all jobs with count 0, in the order they appear in
jobs. - Repeatedly remove the front job and append it to
full_order. Then go through the entries ofrequiresin their given order. For each entry whose prerequisite is this job, decrease the dependent's count by one, and enqueue it when its count reaches 0. - If
full_orderends up shorter thanjobs, a cycle exists.
rerun_order is the affected jobs listed in the same relative order as in full_order.
Constraints
0 <= len(jobs) <= 10^50 <= len(requires) <= 2 * 10^50 <= len(modified) <= 10^5- Job names are unique, non-empty strings.
- Aim for time and memory linear in the number of jobs plus dependencies.
Examples
Example 1
Input: order_jobs_and_reruns(['build', 'test', 'package', 'docs'], [['test', 'build'], ['package', 'test']], ['test'])
Output: [['build', 'docs', 'test', 'package'], ['test', 'package']]
Example 2
Input: order_jobs_and_reruns(['a', 'b', 'c'], [['b', 'a'], ['c', 'b']], ['a'])
Output: [['a', 'b', 'c'], ['a', 'b', 'c']]
Example 3
Input: order_jobs_and_reruns(['a', 'b', 'c'], [['b', 'a'], ['a', 'b']], ['a'])
Output: [['CYCLE'], []]
Example 4
Input: order_jobs_and_reruns([], [], [])
Output: [[], []]
Hints
Hint 1
Treat each pair as a directed edge from prerequisite to dependent. Keep an adjacency list and a count of unmet prerequisites per job.
Hint 2
Kahn's algorithm gives a valid order, and if it cannot place every job, the graph has a cycle.
Hint 3
Affected jobs are everything reachable from the modified jobs along the prerequisite-to-dependent edges. A BFS or DFS with a visited set finds them, and repeated names are harmless.
Hint 4
You do not need to sort the affected jobs again. Filtering the full valid order down to the affected set preserves all ordering constraints among them.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the jobs as a directed graph with an edge from each prerequisite to the job that depends on it.
-
Ordering and cycle detection (Kahn's algorithm). Count each job's unmet prerequisites. Start with the jobs that have none, and repeatedly take one off a FIFO queue, append it to the order, and decrement the counts of its dependents. A dependent whose count reaches zero joins the queue. If the final order holds fewer jobs than the input, the leftover jobs are on or behind a cycle, so return
[["CYCLE"], []]. A self-dependency means a job's count never reaches zero, so it is caught too. Duplicate pairs are counted and decremented the same number of times, so they stay consistent. -
Affected set (reachability). Run a BFS from every modified job (skipping duplicates through a visited set) along the prerequisite-to-dependent edges. Everything visited must rerun: the modified jobs plus all direct and indirect dependents.
-
Rerun order. Filter the full order down to the affected jobs. If job B depends on job A and both are affected, A appears before B in the full order, so it still does in the filtered list. Unaffected prerequisites are skipped, as the rules allow.
Why it is correct
Kahn's algorithm emits a job only after all its prerequisites, and it emits every job exactly when the graph is acyclic. The BFS visits exactly the set of nodes reachable from the modified jobs, which is the definition of the jobs needing a rerun. A subsequence of a valid topological order is still valid for the induced subgraph.
Complexity
Time is O(V + E), where V is the number of jobs and E the number of dependency pairs. Space is O(V + E) for the adjacency lists, counts, queue and visited set.
Reference solution
from typing import List
from collections import deque, defaultdict
def order_jobs_and_reruns(jobs: List[str], requires: List[List[str]], modified: List[str]) -> List[List[str]]:
if not jobs:
return [[], []]
dependents = defaultdict(list)
pending = {job: 0 for job in jobs}
for job, prereq in requires:
dependents[prereq].append(job)
pending[job] += 1
queue = deque(job for job in jobs if pending[job] == 0)
full_order = []
while queue:
cur = queue.popleft()
full_order.append(cur)
for nxt in dependents[cur]:
pending[nxt] -= 1
if pending[nxt] == 0:
queue.append(nxt)
if len(full_order) != len(jobs):
return [["CYCLE"], []]
affected = set()
stack = deque()
for job in modified:
if job not in affected:
affected.add(job)
stack.append(job)
while stack:
cur = stack.popleft()
for nxt in dependents[cur]:
if nxt not in affected:
affected.add(nxt)
stack.append(nxt)
rerun_order = [job for job in full_order if job in affected]
return [full_order, rerun_order]