Deadline-First Job Queue with Prerequisite Gating
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate a job queue where jobs unlock after their prerequisites are consumed, always serving the earliest-deadline unlocked job; tests heaps, dependency counting, and tie-breaking.
You are simulating a job queue in which some jobs cannot be served until other jobs have been served first. You are given a list of operations and a matching list of arguments, and you must return the result of each operation in order.
Operations
Each entry of operations is one of two strings:
"AddTasks": the corresponding entry ofargumentsis a list whose first element is a list of task dictionaries. Add all of those tasks to the system, in the order given. The result recorded for this operation isNone."ConsumeTask": the corresponding entry ofargumentsis an empty list. Remove one task from the system and record that task's full dictionary as the result. If there is no eligible task, record the string"NO_TASK"instead.
Task dictionaries
Each task is a dictionary with these keys:
id: a unique identifier for the task.ddl: an integer deadline. A smaller value means an earlier deadline.subTasks: a list of ids of prerequisite tasks. This key may be missing, which is the same as an empty list. The list may contain the same id more than once, and repeats count as a single prerequisite.
Rules
- A task is eligible once every one of its prerequisites has already been consumed. A task with no prerequisites is eligible as soon as it is added.
- A prerequisite may be added in a later
AddTaskscall than the task that depends on it. Until that prerequisite has been added and consumed, the dependent task is not eligible. A prerequisite that is never added blocks its dependents forever. - A prerequisite that was already consumed before the dependent task was added counts as satisfied.
ConsumeTaskselects the eligible task with the smallestddl, removes it, and returns it.- If several eligible tasks share the smallest
ddl, choose the one that became eligible earliest. A task becomes eligible at the moment it is added (if it has no unmet prerequisites) or at the moment its last unmet prerequisite is consumed. Tasks that become eligible during the sameAddTaskscall are ordered by their position in the added list. Tasks unlocked by a single consume are ordered by the order in which they were registered as waiting on the consumed task. - Task ids are unique and the dependency relationships contain no cycles.
Return a list with one result per operation, in the same order as operations.
Constraints
len(operations) == len(arguments).- Every operation is
"AddTasks"or"ConsumeTask". - Task ids are unique across the whole run, and the dependencies are acyclic.
ddlvalues are integers.- Aim for roughly logarithmic cost per consume rather than rescanning every pending task.
Examples
Example 1
Input: simulate_job_queue(['AddTasks', 'ConsumeTask', 'ConsumeTask', 'ConsumeTask'], [[[{'id': 'A', 'ddl': 5, 'subTasks': []}, {'id': 'B', 'ddl': 2, 'subTasks': ['A']}, {'id': 'C', 'ddl': 3, 'subTasks': []}]], [], [], []])
Output: [None, {'id': 'C', 'ddl': 3, 'subTasks': []}, {'id': 'A', 'ddl': 5, 'subTasks': []}, {'id': 'B', 'ddl': 2, 'subTasks': ['A']}]
Example 2
Input: simulate_job_queue(['AddTasks', 'AddTasks', 'ConsumeTask', 'ConsumeTask'], [[[{'id': 'A', 'ddl': 4, 'subTasks': []}]], [[{'id': 'B', 'ddl': 1, 'subTasks': ['A']}]], [], []])
Output: [None, None, {'id': 'A', 'ddl': 4, 'subTasks': []}, {'id': 'B', 'ddl': 1, 'subTasks': ['A']}]
Hints
Hint 1
Think of each pending task as either blocked or ready. Only ready tasks ever need to be compared by deadline, so keep them in a min-heap.
Hint 2
For every task track how many distinct prerequisites are still unconsumed, and keep a reverse map from a prerequisite id to the tasks waiting on it. A prerequisite may not have been added yet, so register the reverse link anyway unless it is already consumed.
Hint 3
When a task is consumed, decrement the counters of its waiting tasks and push those reaching zero into the heap. Use an increasing counter in the heap entries (deadline, counter, id) to break deadline ties by when the task became eligible.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each pending task is either blocked (at least one prerequisite not yet consumed) or ready (all prerequisites consumed). Only ready tasks compete on deadline, so they live in a min-heap.
We maintain:
tasks: id to task dictionary.remaining: id to the number of distinct unconsumed prerequisites.waiting_on: prerequisite id to the list of task ids waiting for it (reverse edges).consumed: set of consumed ids.ready: min-heap of(ddl, counter, id).
AddTasks. For each task, take the set of its prerequisites (this removes duplicates). For each prerequisite not yet consumed, increase the task's unmet count and record the task in waiting_on[prereq]. If the count is zero, push the task onto the heap. This works even when the prerequisite has not been added yet, because the reverse edge simply waits for it.
ConsumeTask. If the heap is empty, return "NO_TASK". Otherwise pop the minimum, mark it consumed, and return its dictionary. Then go through the tasks waiting on it, decrement their counters, and push any that reach zero.
The counter in each heap entry is increased every time something is pushed (and once per added task). It breaks deadline ties in favor of whichever task became eligible first, and it prevents Python from ever comparing ids or dictionaries.
Why it is correct
Invariant: a task is in the heap exactly when all of its distinct prerequisites have been consumed.
- When a task is added, its counter equals the number of distinct prerequisites not yet consumed, and each of those has a reverse edge to it.
- A prerequisite is consumed at most once, and at that moment it decrements each waiting task exactly once. Deduplication guarantees one edge per distinct prerequisite.
- A task is pushed exactly when its counter reaches zero, so it is never pushed twice.
Given the invariant, the heap minimum is the eligible task with the smallest deadline, with ties broken by eligibility order. A task whose prerequisite is never added stays blocked, as required.
Complexity
Let n be the number of tasks and E the total number of prerequisite links.
- Total time is
O((n + E) log n): every link is processed once, and every task is pushed and popped at most once. - Each
ConsumeTaskcostsO(log n)plus the work to release its dependents. - Space is
O(n + E).
Reference solution
import heapq
from typing import List
def simulate_job_queue(operations: List[str], arguments: List[List[dict]]) -> List[object]:
tasks = {}
remaining = {}
waiting_on = {}
consumed = set()
ready = []
results = []
counter = 0
for operation, args in zip(operations, arguments):
if operation == "AddTasks":
for task in args[0]:
task_id = task["id"]
tasks[task_id] = task
unmet = 0
for prereq in set(task.get("subTasks", [])):
if prereq not in consumed:
unmet += 1
waiting_on.setdefault(prereq, []).append(task_id)
remaining[task_id] = unmet
if unmet == 0:
heapq.heappush(ready, (task["ddl"], counter, task_id))
counter += 1
results.append(None)
elif operation == "ConsumeTask":
if not ready:
results.append("NO_TASK")
continue
_, _, task_id = heapq.heappop(ready)
consumed.add(task_id)
results.append(tasks[task_id])
for dep in waiting_on.pop(task_id, []):
remaining[dep] -= 1
if remaining[dep] == 0:
heapq.heappush(ready, (tasks[dep]["ddl"], counter, dep))
counter += 1
else:
raise ValueError("Unknown operation")
return results