Deadline-Priority Ordering of Dependent Jobs
Heaps, Sorting & SearchAuto-graded · 17 test casesLast updated
Produce an execution order for jobs with prerequisites by always running the ready job with the earliest deadline, breaking ties by id, using topological sort with a heap.
Deadline-Priority Ordering of Dependent Jobs
A job runner receives a list of jobs. Each job is a dictionary with these keys:
task_id: a unique string identifying the job.deadline: an integer.prerequisites: an optional list oftask_idstrings naming jobs that must finish before this job can start. If the key is missing or the list is empty, the job has no prerequisites.
The prerequisite relationships form a directed acyclic graph, and every prerequisite id refers to a job that appears in the input.
Task
Simulate the runner and return the order in which the jobs execute. Jobs run one at a time. At each step:
- A job is ready if all of its prerequisites have already been executed.
- Among all ready jobs, run the one with the smallest
deadline. - If several ready jobs share the smallest deadline, run the one whose
task_idis smallest in ordinary string comparison. - Once a job runs, jobs that were waiting on it may become ready for the next step.
A job never runs before its prerequisites, even if its deadline is earlier than theirs.
Return the list of task_id values in execution order. If the input list is empty, return an empty list.
Constraints
- The number of jobs is
n, with0 <= n <= 10^5. - Deadlines are integers and may be zero or negative.
task_idvalues are unique strings.- The total number of prerequisite entries is at most about
2 * 10^5. - The dependency graph has no cycles, and all prerequisite ids exist in the input.
- A prerequisite list may contain the same id more than once; this must not break the result.
- Aim for roughly
O(n log n + E)time, whereEis the number of prerequisite entries.
Examples
Example 1
Input: order_jobs_by_deadline([{'task_id': 'a', 'deadline': 3, 'prerequisites': []}, {'task_id': 'b', 'deadline': 1, 'prerequisites': []}, {'task_id': 'c', 'deadline': 2, 'prerequisites': []}])
Output: ['b', 'c', 'a']
Example 2
Input: order_jobs_by_deadline([{'task_id': 'compile', 'deadline': 5, 'prerequisites': ['fetch']}, {'task_id': 'fetch', 'deadline': 1, 'prerequisites': []}, {'task_id': 'test', 'deadline': 4, 'prerequisites': ['compile']}, {'task_id': 'docs', 'deadline': 2, 'prerequisites': []}])
Output: ['fetch', 'docs', 'compile', 'test']
Example 3
Input: order_jobs_by_deadline([{'task_id': 'a', 'deadline': 1, 'prerequisites': []}, {'task_id': 'b', 'deadline': 1, 'prerequisites': []}, {'task_id': 'c', 'deadline': 1, 'prerequisites': ['a']}, {'task_id': 'd', 'deadline': 0, 'prerequisites': ['b']}])
Output: ['a', 'b', 'd', 'c']
Hints
Hint 1
A job becomes ready exactly when every prerequisite has run. Track, for each job, how many prerequisites are still unfinished.
Hint 2
Store reverse edges (prerequisite -> jobs that depend on it) so that finishing a job lets you update only its dependents instead of rescanning everything.
Hint 3
Keep the currently ready jobs in a min-heap keyed by the tuple (deadline, task_id); the tuple comparison gives the required tie-break for free.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is Kahn's topological sort, except the queue of ready jobs is replaced by a min-heap.
- Build three maps: each job's deadline, the number of unfinished prerequisites per job (its in-degree), and the reverse adjacency (for each job, the list of jobs that depend on it).
- Put every job with zero unfinished prerequisites into a min-heap keyed by
(deadline, task_id). - Repeatedly pop the smallest entry, append its id to the result, and decrement the counter of each of its dependents. Any dependent whose counter reaches zero is now ready, so push it onto the heap.
- When the heap is empty, the result is the full execution order.
Why it is correct
- Validity: a job is pushed only when its counter reaches zero, which happens only after all its prerequisites were popped and recorded. So no job precedes a prerequisite.
- Completeness: because the graph is acyclic, while unprocessed jobs remain at least one of them has all prerequisites processed, so it is in the heap. The heap therefore does not empty before every job is emitted. Each job is pushed exactly once, when its counter first hits zero.
- Priority: the heap always holds exactly the current ready set, so popping the minimum
(deadline, task_id)is precisely the rule "smallest deadline, ties by smaller id". - Duplicate prerequisites: a repeated prerequisite increments the counter twice and appears twice in the dependents list, so it is decremented twice; the counts stay consistent.
Complexity
With V jobs and E prerequisite entries:
- Time:
O(V log V + E). Each job is pushed and popped once atO(log V), and each edge is processed once inO(1). - Space:
O(V + E)for the maps, the heap and the output.
A naive version that scans the ready list for the minimum each time costs O(V^2) in the worst case; the heap removes that.
Reference solution
import heapq
from typing import List, Dict
def order_jobs_by_deadline(jobs: List[Dict]) -> List[str]:
ids = {job["task_id"] for job in jobs}
pending = {job_id: 0 for job_id in ids}
dependents = {job_id: [] for job_id in ids}
deadlines = {}
for job in jobs:
job_id = job["task_id"]
deadlines[job_id] = job["deadline"]
for pre in job.get("prerequisites", []) or []:
dependents[pre].append(job_id)
pending[job_id] += 1
heap = [(deadlines[j], j) for j, cnt in pending.items() if cnt == 0]
heapq.heapify(heap)
order = []
while heap:
_, job_id = heapq.heappop(heap)
order.append(job_id)
for nxt in dependents[job_id]:
pending[nxt] -= 1
if pending[nxt] == 0:
heapq.heappush(heap, (deadlines[nxt], nxt))
return order