This question evaluates understanding of priority-based scheduling and dependency resolution, focusing on data structures and graph-ordering concepts required to retrieve the smallest-deadline task while respecting prerequisite subtasks.
Design a task processor that supports two operations:
AddTask(task)
: add a new task.
ConsumeTask()
: remove and return the
id
of the next task to execute.
Each task has:
id
: a unique integer
deadline
: an integer priority, where a smaller value means the task should be consumed earlier
subtasks
(optional): a list of task IDs that must be consumed before this task can be consumed
Implement the processor in two stages:
Part 1
Ignore subtasks. ConsumeTask() should always return the ID of the unconsumed task with the smallest deadline.
Part 2
Now each task may include a subtasks field. A task is eligible to be consumed only after all tasks listed in its subtasks have already been consumed. Among all currently eligible tasks, ConsumeTask() should return the one with the smallest deadline.
Assume tasks may be added in any order. If multiple eligible tasks have the same deadline, return the one with the smaller id. If no task is currently eligible, return null.
Example:
{id: 1, deadline: 2, subtasks: [2]}
{id: 2, deadline: 4, subtasks: []}
Then the consume order should be 2, then 1, because task 1 depends on task 2.