KatInterview

Dependency-Aware Job Scheduler with Priority Queues

Data Structure DesignModel answer
MediumModel answerData Structure Designheaptopological-sortgraph

Last 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_ids is 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. If urgent_only=True, only jobs where urgent=True qualify. Returns None when no matching runnable job exists.
  • is_stuck — Returns True when 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)

  1. Deadline — lower deadline value first.
  2. Urgency — urgent=True beats urgent=False.
  3. Registration time — lower registered_at value first.
  4. Job ID — lexicographically smaller ID first.

Additional clarifications

  • Duplicate entries in prereq_ids are treated as a single dependency.
  • A prerequisite that has already finished by the time add_job is called does not block the new job.
  • A prerequisite that was never registered (and never finished) keeps its dependents blocked indefinitely.
  • finish_job may be called on a job that was never claimed via next_job (e.g., an external system completed it); this is valid.
  • Calling finish_job on an already-finished job is a no-op.
  • A job that is currently claimed (returned by next_job but not yet finished) is still "in-progress"; is_stuck must not return True while 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^9
  • 0 <= len(prereq_ids) <= 100
  • add_job is called at most 10^4 times; all job IDs are unique.
  • finish_job is 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.