Dependency-Aware Job Scheduler with Priority Queues
Data Structure DesignModel answerLast updated
Build an in-memory scheduler that tracks job prerequisites, selects the next runnable job by a four-field priority rule, supports filtered queries, and detects deadlocks.
Background
Workflow engines often need to run jobs in dependency order: a job cannot start until every job it depends on has finished. Your task is to build an in-memory JobScheduler class that tracks these relationships, enforces them at runtime, and always picks the most urgent runnable job next.
What to Implement
class JobScheduler:
def add_job(
self,
job_id: str,
prereq_ids: list[str],
deadline: int,
urgent: bool,
registered_at: int,
) -> None: ...
def finish_job(self, job_id: str) -> None: ...
def next_job(self, urgent_only: bool = False) -> str | None: ...
def is_stuck(self) -> bool: ...
Method contracts
add_job— Registers a new job.prereq_idsis the list of jobs that must finish before this one can run. A job whose prerequisites are all already complete (or that has none) becomes immediately runnable.finish_job— Records a job as complete. This may unblock jobs that were waiting on it.next_job— Removes and returns the job ID of the highest-priority runnable job. Ifurgent_only=True, only jobs whereurgent=Truequalify. ReturnsNonewhen no matching runnable job exists.is_stuck— ReturnsTruewhen the scheduler has unfinished jobs but none of them can ever run (because of a dependency cycle or a prerequisite that was never registered and never completed).
Priority rules (applied in order, first difference wins)
- Deadline — lower
deadlinevalue first. - Urgency —
urgent=Truebeatsurgent=False. - Registration time — lower
registered_atvalue first. - Job ID — lexicographically smaller ID first.
Additional clarifications
- Duplicate entries in
prereq_idsare treated as a single dependency. - A prerequisite that has already finished by the time
add_jobis called does not block the new job. - A prerequisite that was never registered (and never finished) keeps its dependents blocked indefinitely.
finish_jobmay be called on a job that was never claimed vianext_job(e.g., an external system completed it); this is valid.- Calling
finish_jobon an already-finished job is a no-op. - A job that is currently claimed (returned by
next_jobbut not yet finished) is still "in-progress";is_stuckmust not returnTruewhile in-progress jobs exist, because they can still finish and unblock others.
Example
s = JobScheduler()
s.add_job("A", [], deadline=100, urgent=False, registered_at=10)
s.add_job("B", ["A"], deadline=50, urgent=True, registered_at=20)
s.add_job("C", [], deadline=100, urgent=True, registered_at=15)
# Runnable now: A and C (B waits on A)
# A vs C: same deadline (100); C is urgent, A is not → C wins
assert s.next_job() == "C"
# A is the only runnable job
assert s.next_job() == "A"
# B is still blocked; nothing else is runnable
assert s.next_job() is None
# A is claimed but not finished → not stuck yet
assert s.is_stuck() == False
s.finish_job("A") # unblocks B
assert s.next_job() == "B"
s.finish_job("B")
assert s.is_stuck() == False # everything done
Constraints
- Job IDs are alphanumeric strings with underscores, length 1–64.
0 <= deadline, registered_at <= 10^90 <= len(prereq_ids) <= 100add_jobis called at most 10^4 times; all job IDs are unique.finish_jobis only called with IDs that were previously added.
Hints
Hint 1
To decide readiness, track how many of each job's prerequisites remain unfinished. When that count hits zero, the job becomes runnable. Decrement the count whenever a prerequisite is finished — this is the core idea behind Kahn's topological-sort algorithm.
Hint 2
Encode the four-field priority rule as a single comparable tuple: (deadline, 0 if urgent else 1, registered_at, job_id). Python compares tuples lexicographically, so pushing this tuple into a min-heap gives you the correct ordering for free.
Hint 3
To handle the urgent_only filter efficiently, maintain two separate heaps — one for urgent jobs and one for normal jobs. An unfiltered query compares the tops of both heaps and pops the smaller; a filtered query only looks at the urgent heap. This avoids popping and re-inserting items that do not match the filter.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is essentially Kahn's algorithm (for dependency tracking) combined with a min-heap (for priority ordering), plus careful lifecycle bookkeeping for the deadlock check.
Core data structures
Dependency tracking (Kahn-style):
_blocked_by: dict[str, int]— number of unfinished prerequisites for each job._unblocks: defaultdict(list)— maps a job ID to the list of jobs waiting on it.
When a job finishes, iterate its _unblocks list, decrement each child's counter, and push any child whose counter reaches zero onto a heap.
Two min-heaps for priority:
Encode priority as a tuple (deadline, 0 if urgent else 1, registered_at, job_id). Maintain two heaps: _urgent_heap (urgent jobs only) and _normal_heap (non-urgent jobs). This makes the urgent_only filter O(log n) instead of requiring a scan or re-insertion loop.
Lifecycle states: BLOCKED → READY → CLAIMED → DONE
Three integer counters (_n_ready, _n_claimed, _n_incomplete) let is_stuck answer in O(1).
Handling ambiguous cases
Before writing any code it is worth pinning these down:
- Prerequisite never added: treated as permanently unfinished. The child stays blocked forever, which eventually surfaces as a stuck scheduler.
- Prerequisite already done at add time: does not count toward the child's block counter.
- Duplicate prerequisite IDs: de-duplicated with a set; otherwise the counter would undercount unmet dependencies.
finish_jobon an unclaimed job: valid. If the job isREADY, its heap entry becomes stale (handled lazily). If it isBLOCKED, it is force-completed.is_stuckwhile jobs are in-progress: must returnFalse. An in-progress job can still finish and unblock others.
Complexity
| Operation | Time |
|---|---|
add_job | O(P + log n), P = number of prerequisites |
finish_job | O(C log n), C = number of children |
next_job | O(log n) amortized (lazy stale-entry removal) |
is_stuck | O(1) |
Space: O(n + E), where E is the total number of prerequisite edges.
Python implementation
import heapq
from collections import defaultdict
BLOCKED, READY, CLAIMED, DONE = range(4)
class JobScheduler:
def __init__(self):
self._key = {} # job_id -> priority tuple
self._status = {} # job_id -> lifecycle state
self._blocked_by = {} # job_id -> unmet prereq count
self._unblocks = defaultdict(list) # prereq_id -> [child_id, ...]
self._urgent_heap = [] # min-heap for urgent jobs
self._normal_heap = [] # min-heap for normal jobs
self._n_ready = 0
self._n_claimed = 0
self._n_incomplete = 0 # BLOCKED + READY + CLAIMED
# ------------------------------------------------------------------
def add_job(self, job_id, prereq_ids, deadline, urgent, registered_at):
self._key[job_id] = (deadline, 0 if urgent else 1, registered_at, job_id)
# de-duplicate and ignore already-finished prerequisites
unmet = {p for p in prereq_ids if self._status.get(p) != DONE}
for p in unmet:
self._unblocks[p].append(job_id)
self._blocked_by[job_id] = len(unmet)
self._n_incomplete += 1
if unmet:
self._status[job_id] = BLOCKED
else:
self._push_ready(job_id)
# ------------------------------------------------------------------
def finish_job(self, job_id):
state = self._status.get(job_id)
if state is None or state == DONE:
return
if state == READY:
self._n_ready -= 1 # heap entry is now stale; lazy removal
elif state == CLAIMED:
self._n_claimed -= 1
self._status[job_id] = DONE
self._n_incomplete -= 1
for child in self._unblocks.pop(job_id, []):
if self._status.get(child) == BLOCKED:
self._blocked_by[child] -= 1
if self._blocked_by[child] == 0:
self._push_ready(child)
# ------------------------------------------------------------------
def next_job(self, urgent_only=False):
self._drain_stale(self._urgent_heap)
self._drain_stale(self._normal_heap)
if urgent_only:
heap = self._urgent_heap if self._urgent_heap else None
elif self._urgent_heap and self._normal_heap:
heap = (self._urgent_heap
if self._urgent_heap[0] < self._normal_heap[0]
else self._normal_heap)
else:
heap = self._urgent_heap or self._normal_heap or None
if heap is None:
return None
job_id = heapq.heappop(heap)[-1]
self._status[job_id] = CLAIMED
self._n_ready -= 1
self._n_claimed += 1
return job_id
# ------------------------------------------------------------------
def is_stuck(self):
return (self._n_incomplete > 0
and self._n_ready == 0
and self._n_claimed == 0)
# ------------------------------------------------------------------
# helpers
def _push_ready(self, job_id):
self._status[job_id] = READY
self._n_ready += 1
key = self._key[job_id]
# key[1] is 0 for urgent, 1 for normal
if key[1] == 0:
heapq.heappush(self._urgent_heap, key)
else:
heapq.heappush(self._normal_heap, key)
def _drain_stale(self, heap):
while heap:
job_id = heap[0][-1]
if self._status.get(job_id) == READY:
break
heapq.heappop(heap)
Common mistakes
- Not de-duplicating
prereq_ids: the block counter undershoots and jobs never become ready. - Counting in-progress jobs as stuck:
is_stuckmust check_n_claimed == 0, not just_n_ready == 0. - Single heap with filter re-insertion: popping items that do not match
urgent_onlyand pushing them back is O(n log n) per call and easy to get wrong. Two heaps eliminates both problems. - Eager stale-entry removal: trying to find and remove a heap entry when a job is force-completed is O(n). Lazy removal (skip it when it surfaces) keeps every operation O(log n).