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:
- Pick the eligible task with the smallest
"deadline". - 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 totasks, and the prerequisite graph is guaranteed to contain no cycles.
Step-by-step walkthrough
Understand the problem and greedy choice rule
Each entry in
taskscarries 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 smallestid.Look at Example 1 to see why sorting all tasks by
deadlineonce 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
20has the smallest deadline (3) in the entire input, yet it cannot run until Task10completes. - Between the two initially eligible tasks (
30withd = 7and10withd = 12), Task30wins (7 < 12), which immediately unlocks Task40(d = 9). Task40then beats waiting Task10(9 < 12), followed by10and finally20— giving[30, 40, 10, 20].
- Task
Why scanning all remaining tasks each round is too slow
A direct brute-force loop keeps a
doneset and repeatsntimes: scan every unprocessed task, verify whether all IDs intask["prerequisites"]are indone, and select the ready task with the minimum(deadline, id).With up to
n = 10^5tasks, scanningO(n)tasks acrossnrounds performs on the order of10^{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.
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_idmeans "prereq_idmust execute beforetask_id": -in_degree[task_id]: how many distinct prerequisites oftask_idare still unfinished. A task is eligible if and only ifin_degree[task_id] == 0. -dependents[prereq_id]: the list of tasks directly waiting onprereq_id. Whenprereq_idfinishes, we decrementin_degreefor each task independents[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'sheapqmin-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_degreereaches0once, so each task is pushed onto and popped fromready_heaponce inO(log n)time.Build the dependency graph and seed the heap
We use dictionaries keyed by
task_idinstead of0..n-1list indices because task IDs can be negative, zero, or large non-contiguous integers. We also register everytask_idin Phase 1 before wiring edges in Phase 2, because a prerequisite task might appear later intasksthan 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))Run the priority-queue loop and trace Example 1 & Example 2
While
ready_heapis non-empty, pop the smallest(deadline, current_id)pair, appendcurrent_idtoexecution_order, and decrementin_degree[next_id]for each dependent task. Whenever a dependent'sin_degreehits0, push(deadline[next_id], next_id)ontoready_heapso 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_heapstarts with[(6, 2), (6, 4)]:(6, 2)pops first by tie-breaker (in_degree[5]drops2 -> 1), then(6, 4)pops (in_degree[5]drops1 -> 0, pushing(1, 5)), and finally(1, 5)pops — returning[2, 4, 5].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 inO(n + P)time. Because the graph has no cycles, each of thentasks reachesin_degree == 0once, so it is pushed ontoready_heaponce (O(log n)) and popped once (O(log n)), totalingO(n log n), while each unique prerequisite link triggers oneO(1)decrement (O(P)total). - Space:
O(n + P). Thein_degree,deadline,ready_heap, andexecution_orderstructures hold at mostnentries each (O(n)), and thedependentslists hold one integer per unique prerequisite link (O(P)).
Edge cases
- Single task (
len(tasks) == 1): Starts within_degree == 0, entersready_heapimmediately, and returns[task["id"]]. - All tasks have empty
prerequisites: Every task entersready_heapin 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 smallertask_id. - Urgent task unlocked mid-run: When finishing a prerequisite unlocks a task whose deadline beats tasks already waiting in
ready_heap(such as Task40jumping ahead of Task10in Example 1), the newly pushed tuple rises ahead of them immediately. - Multi-prerequisite convergence (diamond graph): If Task
5lists[2, 4],in_degree[5]starts at2and only reaches0after both2and4have 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 withset(task["prerequisites"])ensures1is counted once inin_degreeand wired once independents. - Deep chain of
10^5tasks: Ourwhile ready_heap:loop is purely iterative, so it never risks hitting Python's1,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
tasksbydeadlineup front: A task with an early deadline cannot leapfrog an unfinished prerequisite with a later deadline (such as Task20waiting on Task10in Example 1). - Pushing
(deadline, task_dict)ontoheapq: When two tasks share the samedeadline, Python tries to break the tie by comparing the second tuple element (dict < dict), which raisesTypeError: '<' not supported between instances of 'dict' and 'dict'. Always push(deadline, task_id). - Assuming task IDs are
0 .. n - 1or1 .. n: Indexing a fixed-size list bytask["id"]crashes or silently wraps around on negative or large IDs (id = -1indexes the last element in Python!). - Wiring
dependents[prereq_id]in a single pass without pre-initializing keys: Ifdependentsonly creates lists as tasks are visited, encountering a prerequisite that appears later intasksraisesKeyError.
Alternative approaches
- Brute-force scan on each round: Repeatedly scan all unfinished tasks to pick the ready one with minimum
(deadline, id)inO(n * (n + P))time. Too slow forn = 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 sameO(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_degreecounters remain positive and they never enterready_heap. Right afterwhile ready_heap:finishes, checkif 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 remainingin_degree[t] > 0nodes 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 toBtasks forBparallel workers fromready_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 toO(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_timeclock from one completion timestamp to the next) backed by two min-heaps:ready_heapkeyed by(deadline, id)for unlocked tasks, andrunning_heapkeyed by(finish_time, id)for tasks executing on up toWworkers. Whenever free workers and ready tasks both exist, pop fromready_heapand push(current_time + duration, id)ontorunning_heap; otherwise advancecurrent_timeto the earliestfinish_timeinrunning_heap, decrementin_degreeon 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 dependentsv) before running.
Follow-up questions
- What change is needed if the input is no longer guaranteed to be acyclic and you must report dependency cycles?
- Suppose ready tasks are dispatched in waves or fixed-size parallel batches—how does that affect the overall runtime complexity?
- How would your scheduler architecture change if each task also takes a positive runtime duration on a pool of workers?
Similar questions
- Continuous Analog Clock Angle with Milliseconds
- Merge Continuous Party Spans by Neighborhood
- Lowest Common Ancestor in an N-ary Tree
- Deadline Task Scheduler with Prerequisites
- Priority Task Scheduler with Dynamic Dependencies
- Scaled Dot-Product Attention and Token Sampling
More Scale AI interview questions
- Four-Player Trick-Taking Card Game Simulator Medium
- Deadline Task Scheduler with Prerequisites Easy
- Structured Behavioral Stories Across Core Engineering Themes Easy Pro
- Concurrent CSV-to-JSONL Text Classification Pipeline Easy Pro
- Continuous Analog Clock Angle with Milliseconds Medium Pro
- Merge Continuous Party Spans by Neighborhood Medium Pro
- Distributed Fault-Tolerant Task and Cron Scheduler Easy Pro
- Dependency-Aware Streaming Task Scheduler Easy Pro
- Production Pipeline for a Hosted LLM Feature Easy Pro
- Metrics-Grounded Engineering Project Deep Dive Easy Pro