Deadline-Driven Task Processor

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Design a dependency-respecting job scheduler that decides the execution sequence for a collection of tasks. Each entry in tasks is a dictionary with three keys:

  • "id": a unique integer identifying the task.
  • "deadline": an integer representing when the task is due.
  • "prerequisites": a list of integer task IDs that must finish before this task may start.

A task becomes eligible once every task listed in its "prerequisites" has already been executed (tasks with an empty "prerequisites" list are eligible from the start). At each step, select one task from the currently eligible pool using two rules:

  1. Pick the eligible task with the smallest "deadline".
  2. If two or more eligible tasks share that smallest "deadline", break the tie by picking the one with the smallest "id".

Implement:

def process_tasks(tasks: List[Dict]) -> List[int]:

Return a list containing every task "id" in the exact order the tasks are executed.

Examples

Example 1

Input:  tasks = [
            {"id": 10, "deadline": 12, "prerequisites": []},
            {"id": 20, "deadline": 3,  "prerequisites": [10]},
            {"id": 30, "deadline": 7,  "prerequisites": []},
            {"id": 40, "deadline": 9,  "prerequisites": [30]}
        ]
Output: [30, 40, 10, 20]

At the start, only tasks 10 (deadline = 12) and 30 (deadline = 7) are eligible—task 20 has the earliest deadline (3) overall, yet cannot run until 10 finishes. Task 30 runs first and unlocks 40 (deadline = 9), which beats waiting task 10 (9 < 12) and runs second. Task 10 runs third, unlocking 20 to run fourth.

Example 2

Input:  tasks = [
            {"id": 4, "deadline": 6, "prerequisites": []},
            {"id": 2, "deadline": 6, "prerequisites": []},
            {"id": 5, "deadline": 1, "prerequisites": [2, 4]}
        ]
Output: [2, 4, 5]

Tasks 4 and 2 are both immediately eligible with tied deadlines (6), so smaller ID 2 runs first, followed by 4. Only after both prerequisites have completed does task 5 become eligible and run last.

Constraints

  • 1 <= len(tasks) <= 10^5
  • Every "id" and "deadline" is an integer (negative, zero, or positive), and all "id" values are distinct.
  • Every ID inside "prerequisites" belongs to tasks, and the prerequisite graph is guaranteed to contain no cycles.

Step-by-step walkthrough

  1. Understand the problem and greedy choice rule

    Each entry in tasks carries three fields: a unique integer "id", an integer "deadline", and a list of "prerequisites" (IDs of tasks that must finish before this task may start).

    At every step, we inspect only the tasks that are currently eligible (every prerequisite has already executed) and pick the one with the smallest deadline, breaking ties by the smallest id.

    Look at Example 1 to see why sorting all tasks by deadline once up front fails:

      Task 30 (d = 7) ──unlocks──> Task 40 (d = 9)
      [eligible at start]          [blocked by 30]
    
      Task 10 (d = 12) ──unlocks──> Task 20 (d = 3)
      [eligible at start]           [BLOCKED by 10!]
    
    • Task 20 has the smallest deadline (3) in the entire input, yet it cannot run until Task 10 completes.
    • Between the two initially eligible tasks (30 with d = 7 and 10 with d = 12), Task 30 wins (7 < 12), which immediately unlocks Task 40 (d = 9). Task 40 then beats waiting Task 10 (9 < 12), followed by 10 and finally 20 — giving [30, 40, 10, 20].
  2. Why scanning all remaining tasks each round is too slow

    A direct brute-force loop keeps a done set and repeats n times: scan every unprocessed task, verify whether all IDs in task["prerequisites"] are in done, and select the ready task with the minimum (deadline, id).

    With up to n = 10^5 tasks, scanning O(n) tasks across n rounds performs on the order of 10^{10} checks — far too slow.

    Notice the two quantities that brute-force loop wastes time recomputing: 1. Eligibility: A task's status only changes when one of its prerequisites finishes. 2. Smallest deadline: Only one task leaves the ready pool and a handful of newly unlocked tasks enter at each step, so we do not need to re-scan the entire waiting pool.

  3. Key idea: Kahn's topological sweep with a `(deadline, id)` min-heap

    Model the tasks as a directed graph where an edge prereq_id -> task_id means "prereq_id must execute before task_id": - in_degree[task_id]: how many distinct prerequisites of task_id are still unfinished. A task is eligible if and only if in_degree[task_id] == 0. - dependents[prereq_id]: the list of tasks directly waiting on prereq_id. When prereq_id finishes, we decrement in_degree for each task in dependents[prereq_id]. - ready_heap: rather than the first-in-first-out queue used in plain Kahn's algorithm, we keep all eligible tasks in Python's heapq min-heap as (deadline[task_id], task_id) pairs:

    Python compares tuples element by element from left to right:
      (7, 30) < (12, 10)   because deadline 7 < 12
      (6,  2) < ( 6,  4)   deadlines tie (6 == 6), so smaller ID 2 < 4 wins!
    

    Because the dependency graph has no cycles, every task's in_degree reaches 0 once, so each task is pushed onto and popped from ready_heap once in O(log n) time.

  4. Build the dependency graph and seed the heap

    We use dictionaries keyed by task_id instead of 0..n-1 list indices because task IDs can be negative, zero, or large non-contiguous integers. We also register every task_id in Phase 1 before wiring edges in Phase 2, because a prerequisite task might appear later in tasks than the task that depends on it.

        # dependents: maps prerequisite_id -> list of task_ids that directly depend on it
        dependents: Dict[int, List[int]] = {}
        # in_degree: maps task_id -> count of distinct prerequisites not yet processed
        in_degree: Dict[int, int] = {}
        # deadline: maps task_id -> integer deadline
        deadline: Dict[int, int] = {}
    
        # Phase 1: Register every task ID up front so prerequisites appearing later in `tasks`
        # already have a list in `dependents` when we wire edges in Phase 2.
        for task in tasks:
            task_id = task["id"]
            deadline[task_id] = task["deadline"]
            dependents[task_id] = []
            in_degree[task_id] = 0
    
        # Phase 2: Build directed edges `prereq_id -> task_id` and record each task's in-degree.
        for task in tasks:
            task_id = task["id"]
            unique_prereqs = set(task["prerequisites"])  # deduplicate any repeated prerequisite IDs
            in_degree[task_id] = len(unique_prereqs)
            for prereq_id in unique_prereqs:
                dependents[prereq_id].append(task_id)
    
        # Phase 3: Seed the min-heap with every task that starts with 0 prerequisites.
        # Storing (deadline, task_id) pops earliest deadline first, breaking ties by smaller ID.
        ready_heap: List[Tuple[int, int]] = []
        for task_id, remaining_prereqs in in_degree.items():
            if remaining_prereqs == 0:
                heapq.heappush(ready_heap, (deadline[task_id], task_id))
    
  5. Run the priority-queue loop and trace Example 1 & Example 2

    While ready_heap is non-empty, pop the smallest (deadline, current_id) pair, append current_id to execution_order, and decrement in_degree[next_id] for each dependent task. Whenever a dependent's in_degree hits 0, push (deadline[next_id], next_id) onto ready_heap so it competes immediately on the very next step:

        # Phase 4: Repeatedly execute the most urgent available task and unlock its dependents.
        execution_order: List[int] = []
        while ready_heap:
            _, current_id = heapq.heappop(ready_heap)
            execution_order.append(current_id)
    
            for next_id in dependents[current_id]:
                in_degree[next_id] -= 1
                # As soon as the last prerequisite finishes, `next_id` becomes available immediately.
                if in_degree[next_id] == 0:
                    heapq.heappush(ready_heap, (deadline[next_id], next_id))
    

    Let's trace Example 1 (10 (d=12, pre=[]), 20 (d=3, pre=[10]), 30 (d=7, pre=[]), 40 (d=9, pre=[30])):

    Round  ready_heap before pop   Popped  in_degree updates              execution_order
    -----  ----------------------  ------  -----------------------------  ------------------
    1      [(7, 30), (12, 10)]     30      40: 1 -> 0 (push (9, 40))      [30]
    2      [(9, 40), (12, 10)]     40      (no dependents)                [30, 40]
    3      [(12, 10)]              10      20: 1 -> 0 (push (3, 20))      [30, 40, 10]
    4      [(3, 20)]               20      (no dependents)                [30, 40, 10, 20]
    

    And in Example 2 (4 (d=6, pre=[]), 2 (d=6, pre=[]), 5 (d=1, pre=[2, 4])), ready_heap starts with [(6, 2), (6, 4)]: (6, 2) pops first by tie-breaker (in_degree[5] drops 2 -> 1), then (6, 4) pops (in_degree[5] drops 1 -> 0, pushing (1, 5)), and finally (1, 5) pops — returning [2, 4, 5].

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import heapq
    
    
    def process_tasks(tasks: List[Dict]) -> List[int]:
        # dependents: maps prerequisite_id -> list of task_ids that directly depend on it
        dependents: Dict[int, List[int]] = {}
        # in_degree: maps task_id -> count of distinct prerequisites not yet processed
        in_degree: Dict[int, int] = {}
        # deadline: maps task_id -> integer deadline
        deadline: Dict[int, int] = {}
    
        # Phase 1: Register every task ID up front so prerequisites appearing later in `tasks`
        # already have a list in `dependents` when we wire edges in Phase 2.
        for task in tasks:
            task_id = task["id"]
            deadline[task_id] = task["deadline"]
            dependents[task_id] = []
            in_degree[task_id] = 0
    
        # Phase 2: Build directed edges `prereq_id -> task_id` and record each task's in-degree.
        for task in tasks:
            task_id = task["id"]
            unique_prereqs = set(task["prerequisites"])  # deduplicate any repeated prerequisite IDs
            in_degree[task_id] = len(unique_prereqs)
            for prereq_id in unique_prereqs:
                dependents[prereq_id].append(task_id)
    
        # Phase 3: Seed the min-heap with every task that starts with 0 prerequisites.
        # Storing (deadline, task_id) pops earliest deadline first, breaking ties by smaller ID.
        ready_heap: List[Tuple[int, int]] = []
        for task_id, remaining_prereqs in in_degree.items():
            if remaining_prereqs == 0:
                heapq.heappush(ready_heap, (deadline[task_id], task_id))
    
        # Phase 4: Repeatedly execute the most urgent available task and unlock its dependents.
        execution_order: List[int] = []
        while ready_heap:
            _, current_id = heapq.heappop(ready_heap)
            execution_order.append(current_id)
    
            for next_id in dependents[current_id]:
                in_degree[next_id] -= 1
                # As soon as the last prerequisite finishes, `next_id` becomes available immediately.
                if in_degree[next_id] == 0:
                    heapq.heappush(ready_heap, (deadline[next_id], next_id))
    
        return execution_order
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of planning university classes where each course has prerequisite classes and a target semester to finish by (its deadline). Even if Compilers has the earliest deadline (3), you cannot enroll in it before completing Intro Programming (deadline = 12). Instead of re-reading the entire course catalog after every single class you finish, you jot a "prerequisites remaining" count on each course and place every currently unlocked course (0 prerequisites remaining) into a priority inbox sorted by earliest deadline. Each time you finish the top course from that inbox, you subtract 1 from every follow-up course waiting on it, immediately dropping any course whose count hits 0 into the priority inbox.

Why do simpler approaches fail? Sorting all tasks by (deadline, id) once up front ignores dependencies and tries to execute locked tasks before their prerequisites. Conversely, scanning all remaining tasks on every step to check whose prerequisites are satisfied takes O(n^2) time, reaching 10^{10} operations for n = 10^5 tasks. Modeling the input as a directed acyclic graph (DAG) (a network of one-way prerequisite links with no circular loops) and pairing Kahn's algorithm (a topological sort technique — ordering nodes so every prerequisite precedes its dependents — driven by each node's in-degree, its count of unfinished prerequisites) with a min-heap (a binary-tree priority queue that pops the smallest (deadline, task_id) tuple in O(log n) time) selects the exact right task at every step.

Here is how Example 1 (10 at d=12, 20 at d=3 needing [10], 30 at d=7, 40 at d=9 needing [30]) plays out:

Initial state:
  in_degree = {10: 0, 20: 1, 30: 0, 40: 1}
  dependents = {10: [20], 20: [], 30: [40], 40: []}
  ready_heap = [(7, 30), (12, 10)]

Step 1: Pop (7, 30)  -> run 30; in_degree[40]: 1 -> 0  -> push (9, 40), ready_heap = [(9, 40), (12, 10)]
Step 2: Pop (9, 40)  -> run 40; unlocks nothing        -> ready_heap = [(12, 10)]
Step 3: Pop (12, 10) -> run 10; in_degree[20]: 1 -> 0  -> push (3, 20), ready_heap = [(3, 20)]
Step 4: Pop (3, 20)  -> run 20; ready_heap is empty    -> return [30, 40, 10, 20]

Complexity

Let n be the number of tasks (1 <= n <= 10^5) and P be the total number of prerequisite entries across all tasks.

  • Time: O(n log n + P). Initializing the dictionaries and building reverse adjacency lists scan each task and prerequisite entry once in O(n + P) time. Because the graph has no cycles, each of the n tasks reaches in_degree == 0 once, so it is pushed onto ready_heap once (O(log n)) and popped once (O(log n)), totaling O(n log n), while each unique prerequisite link triggers one O(1) decrement (O(P) total).
  • Space: O(n + P). The in_degree, deadline, ready_heap, and execution_order structures hold at most n entries each (O(n)), and the dependents lists hold one integer per unique prerequisite link (O(P)).

Edge cases

  • Single task (len(tasks) == 1): Starts with in_degree == 0, enters ready_heap immediately, and returns [task["id"]].
  • All tasks have empty prerequisites: Every task enters ready_heap in Phase 3 and pops out sorted by (deadline, id).
  • Tied deadlines (as in Example 2): Python compares (deadline, task_id) tuples element by element, so equal deadlines automatically break ties by smaller task_id.
  • Urgent task unlocked mid-run: When finishing a prerequisite unlocks a task whose deadline beats tasks already waiting in ready_heap (such as Task 40 jumping ahead of Task 10 in Example 1), the newly pushed tuple rises ahead of them immediately.
  • Multi-prerequisite convergence (diamond graph): If Task 5 lists [2, 4], in_degree[5] starts at 2 and only reaches 0 after both 2 and 4 have popped.
  • Unsorted input and arbitrary integer IDs: Initializing all task keys in Phase 1 before wiring edges in Phase 2 handles prerequisites that appear later in tasks, and dictionaries handle negative, zero, or non-contiguous IDs and deadlines cleanly.
  • Duplicate prerequisite ID in a single task ([1, 1]): Deduplicating with set(task["prerequisites"]) ensures 1 is counted once in in_degree and wired once in dependents.
  • Deep chain of 10^5 tasks: Our while ready_heap: loop is purely iterative, so it never risks hitting Python's 1,000-call recursion limit.

Common mistakes

  • Using a FIFO queue (collections.deque) instead of a min-heap: Standard Kahn's algorithm with a queue produces some valid topological order, but ignores the rule to always execute the eligible task with the smallest deadline.
  • Sorting tasks by deadline up front: A task with an early deadline cannot leapfrog an unfinished prerequisite with a later deadline (such as Task 20 waiting on Task 10 in Example 1).
  • Pushing (deadline, task_dict) onto heapq: When two tasks share the same deadline, Python tries to break the tie by comparing the second tuple element (dict < dict), which raises TypeError: '<' not supported between instances of 'dict' and 'dict'. Always push (deadline, task_id).
  • Assuming task IDs are 0 .. n - 1 or 1 .. n: Indexing a fixed-size list by task["id"] crashes or silently wraps around on negative or large IDs (id = -1 indexes the last element in Python!).
  • Wiring dependents[prereq_id] in a single pass without pre-initializing keys: If dependents only creates lists as tasks are visited, encountering a prerequisite that appears later in tasks raises KeyError.

Alternative approaches

  • Brute-force scan on each round: Repeatedly scan all unfinished tasks to pick the ready one with minimum (deadline, id) in O(n * (n + P)) time. Too slow for n = 10^5, though handy as a compact reference check in unit tests.
  • Balanced binary search tree / sorted set: Keeps ready (deadline, id) pairs sorted with the same O(n log n + P) complexity, and is only needed if tasks must be canceled or have their deadlines edited mid-flight.

Follow-up questions

  • What change is needed if the input is no longer guaranteed to be acyclic and you must report dependency cycles? Tasks participating in a cycle (along with any tasks downstream of that cycle) never see all of their prerequisites finish, so their in_degree counters remain positive and they never enter ready_heap. Right after while ready_heap: finishes, check if len(execution_order) < len(tasks): — when true, at least one cycle exists, and you can raise an error or run a three-color DFS over the remaining in_degree[t] > 0 nodes to extract an explicit cycle path.
  • Suppose ready tasks are dispatched in waves or fixed-size parallel batches—how does that affect the overall runtime complexity? Total asymptotic complexity remains O(n log n + P)! Whether each wave pops up to B tasks for B parallel workers from ready_heap, or drains every currently ready task into a wave sorted by (deadline, id) before unlocking the next wave, each task is still inserted and removed once (O(n log n) total) and each dependency link is decremented once (O(P) total); if tasks inside the same parallel wave need no relative ordering at all, replacing the heap with a plain per-wave list reduces runtime to O(n + P).
  • How would your scheduler architecture change if each task also takes a positive runtime duration on a pool of workers? Switch from one-task-per-step pops to an event-driven simulation (advancing a current_time clock from one completion timestamp to the next) backed by two min-heaps: ready_heap keyed by (deadline, id) for unlocked tasks, and running_heap keyed by (finish_time, id) for tasks executing on up to W workers. Whenever free workers and ready tasks both exist, pop from ready_heap and push (current_time + duration, id) onto running_heap; otherwise advance current_time to the earliest finish_time in running_heap, decrement in_degree on its dependents, and repeat. Because a slow task with a loose deadline might block an urgent child task, production schedulers also propagate effective deadlines backward (effective_deadline[u] = min(deadline[u], effective_deadline[v] - duration[v]) across dependents v) before running.

Follow-up questions

Similar questions

More Scale AI interview questions

All 29 Scale AI questions →