Deadline Task Scheduler with Prerequisites

Easy · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Build an in-memory deadline-driven job queue TaskManager together with the replay driver function:

def run_task_manager(operations: List[str], arguments: List[List[dict]]) -> List[object]:

Every job dictionary contains three keys: - "id" (str): distinct string identifier for this job. - "ddl" (int): integer due timestamp (lower numbers indicate tighter urgency, and negative integers are valid). - "subTasks" (List[str]): IDs of upstream jobs that must be consumed before this job becomes eligible to run.

TaskManager exposes two operations that may be interleaved in any order: - AddTasks(tasks: List[Dict[str, Any]]) -> None: registers a batch of job dictionaries. An upstream ID listed in "subTasks" might already have been consumed in an earlier step, might currently be waiting in memory, or might arrive in a later AddTasks batch. Repeated IDs inside the same "subTasks" list only need that upstream job to finish once. - ConsumeTask() -> object: removes and returns the eligible job dictionary that has the minimum "ddl" value among all jobs whose "subTasks" have all been consumed previously. If two eligible jobs share the exact same "ddl", break ties by earliest insertion order across batches (and left to right within a batch). Whenever zero jobs are currently eligible, return the string "NO_TASK".

In run_task_manager(operations, arguments), instantiate one TaskManager and execute each (operations[i], arguments[i]) pair sequentially: - When operations[i] == "AddTasks", pass arguments[i][0] to AddTasks and append None to the output list. - When operations[i] == "ConsumeTask", arguments[i] is []; call ConsumeTask() and append its return value to the output list.

Examples

Example 1

Input:

operations = [
    "AddTasks",
    "ConsumeTask",
    "ConsumeTask",
    "ConsumeTask",
    "ConsumeTask",
    "ConsumeTask",
]
arguments = [
    [[
        {"id": "parse", "ddl": 6, "subTasks": []},
        {"id": "deploy", "ddl": 1, "subTasks": ["build"]},
        {"id": "build", "ddl": 8, "subTasks": ["parse"]},
        {"id": "lint", "ddl": 4, "subTasks": []},
    ]],
    [],
    [],
    [],
    [],
    [],
]

Output:

[
    None,
    {"id": "lint", "ddl": 4, "subTasks": []},
    {"id": "parse", "ddl": 6, "subTasks": []},
    {"id": "build", "ddl": 8, "subTasks": ["parse"]},
    {"id": "deploy", "ddl": 1, "subTasks": ["build"]},
    "NO_TASK",
]

Explanation: At the start, only "lint" (ddl = 4) and "parse" (ddl = 6) have zero unmet prerequisites, while "build" waits on "parse" and "deploy" (ddl = 1) waits on "build". The first ConsumeTask pops "lint", and the second pops "parse", which unlocks "build". Consuming "build" then unlocks "deploy", which runs fourth. On the fifth ConsumeTask, no pending jobs remain, returning "NO_TASK".

Example 2

Input:

operations = [
    "AddTasks",
    "ConsumeTask",
    "AddTasks",
    "ConsumeTask",
    "ConsumeTask",
    "ConsumeTask",
]
arguments = [
    [[{"id": "report", "ddl": 2, "subTasks": ["fetch"]}]],
    [],
    [[
        {"id": "fetch", "ddl": 10, "subTasks": []},
        {"id": "notify", "ddl": 5, "subTasks": []},
    ]],
    [],
    [],
    [],
]

Output:

[
    None,
    "NO_TASK",
    None,
    {"id": "notify", "ddl": 5, "subTasks": []},
    {"id": "fetch", "ddl": 10, "subTasks": []},
    {"id": "report", "ddl": 2, "subTasks": ["fetch"]},
]

Explanation: "report" arrives before its upstream dependency "fetch" has even been registered, so the first ConsumeTask returns "NO_TASK". After "fetch" (ddl = 10) and "notify" (ddl = 5) are added, "notify" runs before "fetch" due to its smaller "ddl". Once "fetch" is consumed, "report" becomes eligible and runs on the final call.

Constraints

  • 1 <= len(operations) == len(arguments) <= 5 * 10^4.
  • Total number of jobs added across all "AddTasks" calls is at most 2.5 * 10^4.
  • Total number of prerequisite references across all "subTasks" lists is at most 5 * 10^4.
  • Every job "id" added across the entire run is unique, "ddl" is a signed integer (-10^9 <= ddl <= 10^9), and the overall dependency graph contains no cycles.

Step-by-step walkthrough

  1. Understand the job rules and input shape

    Each job is represented as a dictionary with three keys: - "id": a unique string identifier (such as "parse" or "deploy"). - "ddl": an integer due timestamp (smaller number = higher urgency). - "subTasks": a list of upstream job IDs that must already be consumed before this job is eligible to run.

    We need a TaskManager class supporting two methods across any sequence of interleaved calls: - AddTasks(tasks): register a batch of job dictionaries (returns None). - ConsumeTask(): remove and return the currently eligible job with the smallest ddl, or "NO_TASK" if zero eligible jobs exist right now.

    Example 1 illustrates the central trap:

    lint  (ddl = 4, subTasks = [])
    parse (ddl = 6, subTasks = [])  --->  build (ddl = 8, ["parse"])  --->  deploy (ddl = 1, ["build"])
    
    Even though "deploy" has the earliest deadline (1), it is BLOCKED until "parse" and "build" finish!
    Valid execution order:  lint (4)  -->  parse (6)  -->  build (8)  -->  deploy (1)  -->  "NO_TASK"
    

    Notice also how jobs can arrive across multiple AddTasks calls (as in Example 2): - If "fetch" was already consumed earlier and "report" (needing "fetch") arrives in a later batch, "report" is eligible immediately. - If "report" (needing "fetch") arrives before "fetch" has been consumed — or even before "fetch" has been added at all — "report" is blocked and must wait until "fetch" is added and consumed.

  2. Start with brute force to see what work is wasted

    The simplest idea is to store a list pending of unconsumed tasks and a set consumed of finished task IDs. On every ConsumeTask() call, loop through every task in pending, check whether every ID in task["subTasks"] is inside consumed, and pick the ready task with the smallest ddl.

    Why is that too slow? If N tasks are added and consumed one by one, the first consume scans N tasks, the second scans N - 1 tasks, and so on — O(N^2) task scans plus repeated checks over subTasks lists. Almost all of that scanning is wasted: when task X finishes, only the tasks that specifically depend on X could possibly become newly executable!

  3. Key idea: in-degree counting + a min-heap of ready tasks

    Instead of re-checking all tasks from scratch, we split pending tasks into two zones:

      +---------------------------------------------+        +------------------------------------+
      |                BLOCKED ZONE                 |        |           READY MIN-HEAP           |
      |                                             |  0     |    Ordered by smallest deadline    |
      |  missing_count["build"]  = 1                | -----> |                                    |
      |  waiting_on["parse"]     = ["build"]        | left   |   top -> (ddl=4, 4, "lint")        |
      +---------------------------------------------+        |          (ddl=6, 1, "parse")       |
                          ^                                  +------------------------------------+
                          | decrement                                       |
                          | waiting_on["parse"]                             | heappop()
                          +-------------------- ConsumeTask() <-------------+
                                             adds ID to `consumed`
    

    We maintain four small structures (this is Kahn's topological sort algorithm, using a min-heap instead of a plain queue so the earliest deadline always comes out first): 1. ready: a min-heap containing only executable tasks (zero unmet prerequisites), ordered by ddl. ConsumeTask() just pops the top in O(log N) time! 2. consumed: a set of task IDs already returned by ConsumeTask(). 3. missing_count[task_id]: for each blocked task, how many unconsumed prerequisites it is still waiting on (its remaining in-degree). 4. waiting_on[prereq_id]: a reverse lookup list of blocked task IDs waiting for prereq_id to finish.

    When ConsumeTask() pops task X, we look up waiting_on[X], subtract 1 from each dependent's missing_count, and the moment any dependent's count hits 0, we push it into ready. Each prerequisite link is checked once on insert and decremented once on finish!

  4. Subtle detail: why heap entries need a tie-breaker counter

    What happens if we push (task["ddl"], task) directly onto Python's heapq and two ready tasks share the same deadline ddl = 5?

    Compare (5, {"id": "S1", ...})  vs  (5, {"id": "S2", ...})
             ^                           ^
          5 == 5  --> Python compares element 1: dict < dict --> TypeError!
    

    Python compares tuples left-to-right. When ddl ties, Python tries to compare the two dict objects, which raises TypeError: '<' not supported between instances of 'dict' and 'dict'.

    We fix this cleanly by keeping an integer counter self.insertion_order (1, 2, 3, ...) and storing 3-tuples (task["ddl"], self.insertion_order, task). Because insertion_order is strictly unique for every added task, Python breaks deadline ties by picking whichever task was added earlier (first-in, first-out) and never compares two dictionaries.

  5. Implement state initialization and AddTasks

    When a new task arrives in AddTasks: 1. Increment self.insertion_order and build entry = (task["ddl"], self.insertion_order, task). 2. Gather all prerequisites from task["subTasks"] that are not in self.consumed into a set called missing_prereqs. - Why a set? If subTasks accidentally lists "A" twice (["A", "A"]), "A" will only be consumed once! Deduplicating ensures missing_count[task_id] matches the exact number of notifications task_id will receive. - Notice also that checking prereq_id not in self.consumed handles prerequisites that are currently pending and prerequisites that haven't even been added yet in a future AddTasks call! 3. If missing_prereqs is empty, push entry straight onto self.ready. Otherwise, store missing_count[task_id], stash blocked_entry[task_id], and append task_id to self.waiting_on[prereq_id] for each missing prerequisite.

    class TaskManager:
        def __init__(self) -> None:
            # ready: min-heap of (ddl, insertion_order, task_dict) for executable tasks.
            self.ready: List[Tuple[int, int, Dict[str, Any]]] = []
    
            # consumed: IDs of tasks already returned by ConsumeTask(), e.g. {"lint", "parse"}.
            self.consumed: Set[str] = set()
    
            # missing_count: blocked task ID -> count of unconsumed prerequisites, e.g. {"build": 1}.
            self.missing_count: Dict[str, int] = {}
    
            # blocked_entry: blocked task ID -> (ddl, insertion_order, task_dict) waiting to enter `ready`.
            self.blocked_entry: Dict[str, Tuple[int, int, Dict[str, Any]]] = {}
    
            # waiting_on: prerequisite ID -> list of blocked task IDs waiting for it, e.g. {"parse": ["build"]}.
            self.waiting_on: Dict[str, List[str]] = {}
    
            # Monotonic counter used to break deadline ties (FIFO) and avoid comparing task dicts.
            self.insertion_order: int = 0
    
        def AddTasks(self, tasks: List[Dict[str, Any]]) -> None:
            for task in tasks:
                self.insertion_order += 1
                task_id = task["id"]
    
                # Including `self.insertion_order` ensures two tasks with equal `ddl` never
                # trigger a TypeError by comparing raw dictionaries in heapq.
                entry = (task["ddl"], self.insertion_order, task)
    
                # Collect distinct prerequisites that have NOT been consumed yet.
                # Using a set deduplicates repeated IDs like subTasks=["A", "A"] so the count
                # matches the exact number of finish notifications this task will receive.
                missing_prereqs: Set[str] = set()
                for prereq_id in task["subTasks"]:
                    if prereq_id not in self.consumed:
                        missing_prereqs.add(prereq_id)
    
                # If all prerequisites are already satisfied, the task is immediately executable.
                if not missing_prereqs:
                    heapq.heappush(self.ready, entry)
                    continue
    
                # Otherwise, park the task in the blocked state and subscribe to each missing prerequisite.
                self.missing_count[task_id] = len(missing_prereqs)
                self.blocked_entry[task_id] = entry
                for prereq_id in missing_prereqs:
                    if prereq_id not in self.waiting_on:
                        self.waiting_on[prereq_id] = []
                    self.waiting_on[prereq_id].append(task_id)
    
  6. Implement ConsumeTask and the operation runner

    In ConsumeTask(): - If self.ready is empty, no pending task has all of its prerequisites satisfied, so return "NO_TASK". - Otherwise, heapq.heappop(self.ready) gives the executable task with the earliest deadline. Record its ID in self.consumed. - Pop self.waiting_on.pop(finished_id, []) to get every blocked task waiting on finished_id (popping also frees that list, since task IDs are unique and finished_id will never be consumed again). Decrement each dependent's missing_count, and when a count reaches 0, move its stashed tuple from self.blocked_entry into self.ready.

    Finally, run_task_manager creates a TaskManager and replays operations and arguments (AddTasks passes args[0] and appends None; ConsumeTask appends the returned task or "NO_TASK").

        def ConsumeTask(self) -> object:
            # Phase 1: If no task has zero unmet prerequisites, nothing can run right now.
            if not self.ready:
                return NO_TASK
    
            # Phase 2: Pop the ready task with the smallest deadline (ties broken by insertion_order).
            ddl, order, task = heapq.heappop(self.ready)
            finished_id = task["id"]
            self.consumed.add(finished_id)
    
            # Phase 3: Notify every blocked task that was waiting on `finished_id`.
            # Popping removes the list so we free memory once `finished_id` is done forever.
            waiting_task_ids = self.waiting_on.pop(finished_id, [])
            for dependent_id in waiting_task_ids:
                self.missing_count[dependent_id] -= 1
                if self.missing_count[dependent_id] == 0:
                    # Last prerequisite just finished: promote this task into the ready min-heap.
                    del self.missing_count[dependent_id]
                    ready_entry = self.blocked_entry.pop(dependent_id)
                    heapq.heappush(self.ready, ready_entry)
    
            return task
    
  7. Trace Example 1 step by step

    Example 1 calls AddTasks with parse(ddl=6, []), deploy(ddl=1, ["build"]), build(ddl=8, ["parse"]), and lint(ddl=4, []), followed by five ConsumeTask calls:

    Step | Call        | ready heap (ddl, ord, id)         | missing_count            | Return
    -----+-------------+-----------------------------------+--------------------------+----------
      1  | AddTasks    | [(4, 4, lint), (6, 1, parse)]     | {"deploy":1, "build":1}  | None
      2  | ConsumeTask | [(6, 1, parse)]                   | {"deploy":1, "build":1}  | lint
      3  | ConsumeTask | [(8, 3, build)]  (build promoted) | {"deploy":1}             | parse
      4  | ConsumeTask | [(1, 2, deploy)] (deploy promoted)| {}                       | build
      5  | ConsumeTask | []                                | {}                       | deploy
      6  | ConsumeTask | []                                | {}                       | "NO_TASK"
    

    Notice Steps 3 and 4: consuming parse drops missing_count["build"] to 0 so (8, 3, build) enters ready, and consuming build drops missing_count["deploy"] to 0 so (1, 2, deploy) enters ready. Once deploy finishes, ready is empty and Step 6 returns "NO_TASK".

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import heapq
    
    NO_TASK = "NO_TASK"
    
    
    class TaskManager:
        def __init__(self) -> None:
            # ready: min-heap of (ddl, insertion_order, task_dict) for executable tasks.
            self.ready: List[Tuple[int, int, Dict[str, Any]]] = []
    
            # consumed: IDs of tasks already returned by ConsumeTask(), e.g. {"lint", "parse"}.
            self.consumed: Set[str] = set()
    
            # missing_count: blocked task ID -> count of unconsumed prerequisites, e.g. {"build": 1}.
            self.missing_count: Dict[str, int] = {}
    
            # blocked_entry: blocked task ID -> (ddl, insertion_order, task_dict) waiting to enter `ready`.
            self.blocked_entry: Dict[str, Tuple[int, int, Dict[str, Any]]] = {}
    
            # waiting_on: prerequisite ID -> list of blocked task IDs waiting for it, e.g. {"parse": ["build"]}.
            self.waiting_on: Dict[str, List[str]] = {}
    
            # Monotonic counter used to break deadline ties (FIFO) and avoid comparing task dicts.
            self.insertion_order: int = 0
    
        def AddTasks(self, tasks: List[Dict[str, Any]]) -> None:
            for task in tasks:
                self.insertion_order += 1
                task_id = task["id"]
    
                # Including `self.insertion_order` ensures two tasks with equal `ddl` never
                # trigger a TypeError by comparing raw dictionaries in heapq.
                entry = (task["ddl"], self.insertion_order, task)
    
                # Collect distinct prerequisites that have NOT been consumed yet.
                # Using a set deduplicates repeated IDs like subTasks=["A", "A"] so the count
                # matches the exact number of finish notifications this task will receive.
                missing_prereqs: Set[str] = set()
                for prereq_id in task["subTasks"]:
                    if prereq_id not in self.consumed:
                        missing_prereqs.add(prereq_id)
    
                # If all prerequisites are already satisfied, the task is immediately executable.
                if not missing_prereqs:
                    heapq.heappush(self.ready, entry)
                    continue
    
                # Otherwise, park the task in the blocked state and subscribe to each missing prerequisite.
                self.missing_count[task_id] = len(missing_prereqs)
                self.blocked_entry[task_id] = entry
                for prereq_id in missing_prereqs:
                    if prereq_id not in self.waiting_on:
                        self.waiting_on[prereq_id] = []
                    self.waiting_on[prereq_id].append(task_id)
    
        def ConsumeTask(self) -> object:
            # Phase 1: If no task has zero unmet prerequisites, nothing can run right now.
            if not self.ready:
                return NO_TASK
    
            # Phase 2: Pop the ready task with the smallest deadline (ties broken by insertion_order).
            ddl, order, task = heapq.heappop(self.ready)
            finished_id = task["id"]
            self.consumed.add(finished_id)
    
            # Phase 3: Notify every blocked task that was waiting on `finished_id`.
            # Popping removes the list so we free memory once `finished_id` is done forever.
            waiting_task_ids = self.waiting_on.pop(finished_id, [])
            for dependent_id in waiting_task_ids:
                self.missing_count[dependent_id] -= 1
                if self.missing_count[dependent_id] == 0:
                    # Last prerequisite just finished: promote this task into the ready min-heap.
                    del self.missing_count[dependent_id]
                    ready_entry = self.blocked_entry.pop(dependent_id)
                    heapq.heappush(self.ready, ready_entry)
    
            return task
    
    
    def run_task_manager(
        operations: List[str],
        arguments: List[List[dict]],
    ) -> List[object]:
        manager = TaskManager()
        results: List[object] = []
    
        for op, args in zip(operations, arguments):
            if op == "AddTasks":
                # For AddTasks, args is [list_of_task_dicts] and the call returns None.
                manager.AddTasks(args[0])
                results.append(None)
            elif op == "ConsumeTask":
                results.append(manager.ConsumeTask())
            else:
                raise ValueError(f"unknown operation: {op}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine registering for university courses where some courses have prerequisites and every course has an exam deadline (ddl). You keep two boards: a Waiting Board for courses you cannot take yet (with a tally of how many prerequisites you still need to pass) and an Available Now Board sorted by earliest exam date. Whenever you pass a course, you do not re-read the entire course catalog — you simply look up which courses were waiting on the course you just finished, cross one tally mark off each of them, and move any course whose tally reaches zero onto the Available Now Board.

Why does the naive approach fall short? Keeping a flat list of pending tasks and scanning all of them on every ConsumeTask() call repeats the same prerequisite checks over and over, taking O(N) work per consume and O(N^2) across N tasks. Putting every task straight into a single deadline-sorted priority queue also fails: if you pop the earliest-deadline task and discover it is still blocked, you have to set it aside, keep popping until you find an executable task, and push all the blocked ones back — which still degrades to O(N log N) on a single ConsumeTask() call.

Tasks and their prerequisites form a directed acyclic graph (DAG) (a network of one-way dependency arrows with no circular loops). We run Kahn's topological sort algorithm (an algorithm that processes nodes only when their count of remaining prerequisites hits zero), swapping its usual queue for a min-heap (a tree-based priority queue that inserts items and pops the smallest key in O(log N) time): - Each blocked task tracks its remaining in-degree (the count of its prerequisites not yet consumed) in missing_count, and subscribes to a reverse adjacency list waiting_on[prereq_id] (a dictionary mapping each prerequisite ID to the list of tasks waiting for it). - Executable tasks (missing_count == 0) live in ready as (ddl, insertion_order, task) tuples so the smallest ddl always sits at the top.

Walk through Example 1's 4-job trace with parse(ddl=6, []), deploy(ddl=1, ["build"]), build(ddl=8, ["parse"]), and lint(ddl=4, []): 1. AddTasks([parse, deploy, build, lint]): lint and parse have zero unmet prerequisites, so ready holds [(4, 4, lint), (6, 1, parse)]. build waits in waiting_on["parse"] (missing_count = 1) and deploy waits in waiting_on["build"] (missing_count = 1). 2. ConsumeTask() #1: pops lint(ddl=4) and marks "lint" consumed. 3. ConsumeTask() #2: pops parse(ddl=6), marks "parse" consumed, decrements missing_count["build"] to 0, and pushes (8, 3, build) into ready. 4. ConsumeTask() #3: pops build(ddl=8), marks "build" consumed, decrements missing_count["deploy"] to 0, and pushes (1, 2, deploy) into ready. 5. ConsumeTask() #4 and #5: pops deploy(ddl=1), then sees ready empty and returns "NO_TASK".

Complexity

Let N be the total number of tasks added across all AddTasks calls and E be the total number of entries across all subTasks lists.

  • Time: O((N + E) + N log N) total across the entire sequence of operations. Each prerequisite link in subTasks is inspected once in O(1) average hash-set time when its task is added, and triggers at most one O(1) decrement when that prerequisite is consumed (O(N + E) total graph work). Each of the N tasks is pushed onto the ready min-heap at most once (O(log N)) and popped at most once (O(log N)), adding O(N log N) total heap work.
  • Space: O(N + E). The ready heap, consumed set, missing_count, and blocked_entry each store at most O(N) entries, while the waiting_on lists store at most E task ID references combined.

Edge cases

  • Empty scheduler or all tasks finished: self.ready is empty, so ConsumeTask() returns "NO_TASK".
  • Pending tasks exist, but every single one is blocked: self.ready is still empty (all pending tasks sit in blocked_entry), so ConsumeTask() rightly returns "NO_TASK".
  • Dependent task added before its prerequisite is added: Because prereq_id not in self.consumed is true even when prereq_id has never been seen yet, the dependent waits safely in waiting_on[prereq_id] until prereq_id arrives in a later AddTasks batch and gets consumed.
  • Prerequisite already consumed in an earlier call: prereq_id in self.consumed is immediately true when the dependent arrives, so the dependent skips waiting_on and enters self.ready right away.
  • Duplicate prerequisite IDs (subTasks = ["A", "A"]): Deduplicating into missing_prereqs as a set counts "A" once, so consuming "A" once unblocks the task cleanly.
  • Equal or negative deadlines: Negative ddl integers sort naturally before 0, and self.insertion_order breaks ties deterministically without comparing dictionaries.

Common mistakes

  • Pushing (ddl, task) without a tie-breaker: Whenever two ready tasks share the same ddl, heapq falls back to comparing the task dictionaries and crashes with TypeError.
  • Setting missing_count[id] = len(task["subTasks"]) while deduplicating waiting_on (or when some prerequisites were already consumed): The count starts too high and never drops to 0, stranding the task forever.
  • Unblocking dependents when a prerequisite is added instead of consumed: Every upstream job in "subTasks" must be consumed before a dependent becomes eligible to run.
  • Ignoring prerequisites not yet added to the manager: Filtering subTasks to IDs currently known to TaskManager mistakenly treats an unadded prerequisite as satisfied and runs the dependent prematurely.
  • Pushing all tasks (including blocked ones) into one heap: Forces ConsumeTask() to pop and re-push arbitrarily many urgent-but-blocked tasks on every call.

Alternative approaches

  • Balanced binary search tree (SortedList): Keeping ready tasks in a sorted tree keyed by (ddl, insertion_order) gives the same O(log N) insert and pop-min bounds as a binary heap, while also supporting O(log N) removal of an arbitrary ready task if a CancelTask(task_id) operation is added later.

Follow-up questions

  • How would you detect and reject dependency cycles if callers could submit invalid graphs? With our in-degree design, a cycle never causes an infinite loop in ConsumeTask(): jobs inside a cycle retain missing_count >= 1, never enter self.ready, and ConsumeTask() safely returns "NO_TASK". If AddTasks must reject a batch that creates a cycle before mutating state, keep forward subTasks edges for unconsumed jobs and run a three-color depth-first search starting from the candidate batch through unconsumed prerequisites; encountering a node currently on the active recursion stack proves a cycle in O(N + E) worst-case time, allowing AddTasks to raise an error cleanly.
  • What if a high-urgency task is stuck behind a low-urgency prerequisite—how could you propagate effective deadlines? Use priority inheritance (effective deadlines): define each job's effective deadline as min(its own ddl, effective ddl of all jobs that depend on it). When an urgent job arrives, walk backward through its unconsumed prerequisites and lower any larger effective deadline to match; because Python's heapq lacks a decrease-key operation, push a fresh (new_effective_ddl, order, task) tuple onto ready and use lazy deletion (discarding stale heap entries on heappop when task["id"] in self.consumed). Clarify with the interviewer before changing this behavior, since the baseline specification ranks eligible jobs strictly by their own "ddl".
  • How would the API and locking change if multiple worker threads execute tasks asynchronously? Split ConsumeTask() into two lifecycle calls: AcquireTask() -> object (which pops the earliest-deadline ready job and marks it IN_PROGRESS, without decrementing dependents yet) and CompleteTask(task_id) (which moves task_id into consumed and decrements waiting_on[task_id]). Guard TaskManager state with a threading.Lock (or threading.Condition if workers block instead of polling "NO_TASK"), and attach a lease expiration timestamp to IN_PROGRESS jobs so a background reaper can return abandoned jobs to ready if a worker crashes.

Follow-up questions

Similar questions

More Scale AI interview questions

All 29 Scale AI questions →