KatInterview

Task Scheduler with Parallel Workers

Heaps, Sorting & SearchAuto-graded · 19 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapsimulationgreedy

Last updated

Simulate dispatching sequential tasks to parallel workers and determine when all work completes.

You are managing a task scheduler that assigns work to a pool of identical workers. You receive a list of integers tasks where tasks[i] represents how long the i-th task takes to complete, and an integer workers indicating how many parallel workers are available.

All workers are ready at time 0 and are numbered from 0 to workers - 1.

Tasks must be assigned in the exact order they appear:

  • Task 0 is assigned first, then task 1, and so on.
  • Each task goes to whichever worker finishes its current work earliest.
  • When multiple workers finish at the same time, assign the task to the worker with the smallest index.
  • A worker executes its assigned task without interruption for the full duration.

Return the total time from 0 until every task has been completed.

Constraints

  • 0 <= len(tasks) <= 10^5
  • 1 <= workers <= 10^5
  • 0 <= tasks[i] <= 10^9
  • The result may exceed 32-bit integer limits

Examples

Example 1

Input: schedule_tasks([3, 2, 4, 1, 5], 2)

Output: 9

Example 2

Input: schedule_tasks([10, 20, 15], 5)

Output: 20

Example 3

Input: schedule_tasks([], 4)

Output: 0

Hints

Hint 1

Tracking which worker becomes available earliest is key—what data structure excels at repeated minimum extraction?

Hint 2

Python tuples compare element-by-element, so a heap of (time, worker_id) pairs naturally implements both the earliest-time rule and the tie-breaking rule.

Hint 3

The last task assigned is not necessarily the last to finish—track the maximum completion time across all assignments.