Total Runtime of Queued Tasks Across Workers

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a queue of task runtimes durations (where durations[i] is the execution length in seconds of task i) and k identical parallel execution nodes numbered 0 through k - 1, compute how many seconds elapse from t = 0 until the entire queue finishes running.

Every node starts idle at t = 0, and tasks are dispatched deterministically without reordering:

  • Tasks leave the queue strictly in index order (0, then 1, then 2, and so forth).
  • Each task goes to whichever node becomes idle at the earliest timestamp.
  • Whenever multiple nodes share the same earliest idle timestamp, pick the node with the smallest index.
  • Once assigned at timestamp s, a node runs that task uninterrupted until s + durations[i] (a task with durations[i] == 0 completes instantaneously at s, leaving that node idle at s).

Implement calculate_makespan(durations, k) and return the overall completion time (or 0 when durations is empty).

Examples

Example 1

Input: durations = [4, 2, 5, 3, 6], k = 2
Output: 13

Walk-through: - t = 0: Node 0 takes task 0 (4s, free at 4), and Node 1 takes task 1 (2s, free at 2). - t = 2: Node 1 becomes free earliest and takes task 2 (5s, free at 7). - t = 4: Node 0 becomes free and takes task 3 (3s, free at 7). - t = 7: Both nodes finish at t = 7; the lowest-index tie-breaker assigns task 4 (6s) to Node 0, finishing at t = 13.

Example 2

Input: durations = [12, 25, 8], k = 6
Output: 25

Walk-through: Six nodes are idle at t = 0, so nodes 0, 1, and 2 start all three tasks immediately at t = 0 while nodes 3..5 remain idle. The slowest task completes at t = 25.

Example 3

Input: durations = [11, 0, 4, 3], k = 2
Output: 11

Walk-through: - t = 0: Node 0 takes task 0 (11s, free at 11), while Node 1 takes task 1 (0s, finishing immediately at t = 0). - Still at t = 0, Node 1 takes task 2 (4s, free at 4), and at t = 4 Node 1 takes task 3 (3s, free at 7). - Node 0 finishes last at t = 11, so the overall completion time is 11.

Constraints

  • 0 <= len(durations) <= 10^5
  • 1 <= k <= 10^5
  • 0 <= durations[i] <= 10^9
  • Total completion time can reach 10^{14}, so 64-bit (or arbitrary-precision) integer arithmetic is required (durations == [] returns 0)

Step-by-step walkthrough

  1. Understand the problem and dispatch rules

    We receive durations (up to 10^5 non-negative task lengths in arrival order) and k (up to 10^5 identical parallel workers numbered 0 through k - 1, all initially idle at t = 0).

    Our goal is to find the overall makespan: how much time passes from t = 0 until the very last task finishes (0 when durations is empty).

    Notice that reordering tasks is not permitted—the dispatch sequence is completely fixed:

    1. Process tasks strictly in arrival order: index 0, then 1, and so on.
    2. Route each task to whichever worker has the smallest free_time.
    3. Whenever several workers share the same free_time, pick the worker with the smallest worker_id.
    4. Once chosen, that worker stays busy from free_time until free_time + duration.

    Because 10^5 tasks can each run for 10^9 seconds on a single worker, the total finish time can reach 10^14, overflowing 32-bit signed integers (~2.1 * 10^9) in C++ or Java; Python integers expand to arbitrary precision automatically.

  2. Why naive worker scans and clock ticking are too slow

    Two straightforward simulations immediately exceed the time budget:

    • Advancing a clock one second at a time: A single task can span 10^9 seconds, and total runtime can hit 10^14 seconds—far too many ticks to loop through.
    • Scanning an array free[0..k-1] on every task: Inspecting all k workers for each of the n tasks costs O(n * k) work. At n = 10^5 and k = 10^5, that reaches 10^10 comparisons.

    Look at what each task really needs from the worker pool: extract the worker with the minimum (free_time, worker_id) and reinsert that worker with its updated finish timestamp.

  3. Key idea: A min-heap of `(free_time, worker_id)` tuples

    A min-heap (provided by Python's heapq module) is a binary tree packed into a list that keeps its smallest item at index 0, letting us pop the minimum and push an updated entry in O(log h) time (for h heap entries).

    Representing each worker as the 2-tuple (free_time, worker_id) makes Python's tuple comparison handle both rules automatically:

    • Compare free_time first (smaller timestamp wins — earliest-idle worker).
    • Break equal free_time ties by worker_id (smaller index wins).

    One extra observation shrinks the heap whenever k vastly exceeds len(durations) (say 3 tasks and k = 100,000): at t = 0, task 0 claims worker 0, task 1 claims worker 1, and task 2 claims worker 2. Workers 3..99,999 will never be touched! Capping the pool at worker_count = min(k, len(durations)) avoids allocating unused workers:

    from typing import List, Tuple
    
    durations = [12, 25, 8]
    k = 100000
    
    worker_count = min(k, len(durations))
    workers: List[Tuple[int, int]] = []
    for worker_id in range(worker_count):
        workers.append((0, worker_id))
    

    Because (0, 0), (0, 1), ..., (0, worker_count - 1) is already sorted in ascending order, every parent entry is <= its children, so workers already satisfies the binary min-heap invariant without calling heapq.heapify().

  4. Dispatch each task and track the running maximum finish time

    For each duration in durations, pop (free_time, worker_id), compute finish_time = free_time + duration, and push (finish_time, worker_id) back onto the heap.

    Why track makespan = max(makespan, finish_time) across every task rather than returning the finish time of the final task in durations? Consider Example 3 (durations = [11, 0, 4, 3] with k = 2):

    Time:      0   1   2   3   4   5   6   7   8   9  10  11
    Worker 0:  [=============== task 0 (11s) ==============]  finishes at t = 11
    Worker 1:  [][=== t2 ===][== t3 ==]                       final task finishes at t = 7!
    

    Task 3 is dispatched last, yet it finishes at t = 7 on Worker 1 while Worker 0 is still busy with task 0 until t = 11. Maintaining the running maximum captures 11 cleanly. Also notice task 1 (0s): finish_time = 0 + 0 = 0, so pushing (0, 1) puts Worker 1 right back at the top of the heap at t = 0.

  5. Trace Example 1 step by step

    Let us trace durations = [4, 2, 5, 3, 6] with k = 2. Initially workers = [(0, 0), (0, 1)] and makespan = 0:

    Timeline:
    Time:      0   1   2   3   4   5   6   7   8   9  10  11  12  13
    Worker 0:  [=== task 0 ===][== t3 ==][====== task 4 ======]   finishes at 4, 7, 13
    Worker 1:  [= t1 =][==== task 2 ====]                         finishes at 2, 7
    
    Heap state trace:
    Task | Duration | Popped (free, id) | Finish | Heap after push     | makespan
    -----+----------+-------------------+--------+---------------------+---------
      0  |    4     | (0, 0)            | 0+4=4  | [(0, 1), (4, 0)]    |    4
      1  |    2     | (0, 1)            | 0+2=2  | [(2, 1), (4, 0)]    |    4
      2  |    5     | (2, 1)            | 2+5=7  | [(4, 0), (7, 1)]    |    7
      3  |    3     | (4, 0)            | 4+3=7  | [(7, 0), (7, 1)]    |    7
      4  |    6     | (7, 0) [tie -> 0] | 7+6=13 | [(7, 1), (13, 0)]   |   13
    

    At t = 7, (7, 0) < (7, 1) breaks the tie in favor of Worker 0, and all five tasks complete by t = 13.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import heapq
    
    
    def calculate_makespan(durations: List[int], k: int) -> int:
        # Guard empty input: with zero jobs, elapsed time from t = 0 is 0.
        if not durations:
            return 0
    
        # Cap initialized workers at len(durations): any worker with index >= len(durations)
        # would never receive a job because each job pops only one idle worker at t = 0.
        worker_count = min(k, len(durations))
    
        # workers: min-heap of (free_time, worker_id) tuples, e.g. [(0, 0), (0, 1)].
        # Because worker_id increases from 0, this list is already sorted and satisfies
        # the binary min-heap invariant without needing heapq.heapify().
        workers: List[Tuple[int, int]] = []
        for worker_id in range(worker_count):
            workers.append((0, worker_id))
    
        # Phase 2: dispatch jobs strictly in queue order and track the latest finish time.
        makespan = 0
        for duration in durations:
            # Tuple order (free_time, worker_id) pops the earliest-free worker first,
            # breaking ties by the smallest worker_id.
            free_time, worker_id = heapq.heappop(workers)
            finish_time = free_time + duration
            heapq.heappush(workers, (finish_time, worker_id))
    
            # Track the running maximum because an earlier long job can finish after
            # a later short job (e.g. durations = [10, 1, 1] with k = 2).
            if finish_time > makespan:
                makespan = finish_time
    
        return makespan
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture k airport check-in counters serving a single FIFO line of travelers (durations). Whenever the person at the head of the line steps forward, they walk to whichever counter opens up earliest (choosing the lowest-numbered counter on a tie), and the check-in hall cannot close until the last busy agent finishes helping their traveler. That closing timestamp—measured from t = 0 until every task finishes—is the makespan.

A naive simulation either ticks a clock second by second (hopeless when a single task can run for 10^9 seconds) or scans all k workers on every task, costing n * k steps—up to 10^10 comparisons when n = 10^5 and k = 10^5. Instead, we maintain workers inside a min-heap (a tree-based priority queue stored in a list that pops its smallest element and inserts an updated element in O(log h) time). Keeping (free_time, worker_id) tuples lets each task pick its next idle worker in at most ~17 comparisons instead of 100,000.

Let us trace Example 1 (durations = [4, 2, 5, 3, 6] on k = 2 workers), starting from heap [(0, 0), (0, 1)]:

  • Task 0 (4s) pops (0, 0) -> finishes at 4, pushes (4, 0); makespan = 4.
  • Task 1 (2s) pops (0, 1) -> finishes at 2, pushes (2, 1); makespan = 4.
  • Task 2 (5s) pops (2, 1) -> finishes at 7, pushes (7, 1); makespan = 7.
  • Task 3 (3s) pops (4, 0) -> finishes at 7, pushes (7, 0); makespan = 7.
  • Task 4 (6s) pops (7, 0) (tie at 7 goes to worker 0) -> finishes at 13, pushes (13, 0); makespan = 13.

Complexity

Let n = len(durations) and h = min(k, n).

  • Time — O(n log h): Building the h initial (0, worker_id) entries in ascending order takes O(h) time, and each of the n tasks runs one heappop and one heappush on a heap of size h, costing O(log h) per task.
  • Space — O(h): The heap holds at most min(k, n) (free_time, worker_id) tuples at any point, so even when k = 100,000 and n = 3, only 3 tuples are allocated.

Edge cases

  • Empty durations ([]): Handled up front by if not durations: return 0.
  • More workers than tasks (k >= n): Only n workers are created at free_time = 0, every task starts at t = 0, and makespan equals max(durations).
  • Single worker (k = 1): The heap has size 1, tasks run back to back, and makespan equals sum(durations).
  • Zero-duration tasks (duration = 0): finish_time = free_time + 0 pushes (free_time, worker_id) back with the unchanged timestamp, keeping that worker immediately available at the same instant.
  • Simultaneous idle times (ties): Tuple comparison (free_time, worker_id) compares worker_id whenever free_time ties, always picking the lowest worker index.
  • 64-bit integer overflow: 10^5 tasks of length 10^9 on k = 1 worker reach 10^14, exceeding 32-bit signed integers (2^31 - 1); Python handles arbitrary-precision integers natively, whereas C++/Java require int64_t / long.

Common mistakes

  • Returning the finish time of the final task in durations: In Example 3 ([11, 0, 4, 3] with k = 2), the final task finishes at t = 7 on Worker 1 while Worker 0 continues running task 0 until t = 11. Always maintain max(makespan, finish_time).
  • Sorting durations before dispatching: Tasks must be dispatched strictly in arrival order; on [1, 1, 2] with k = 2, arrival order yields 3 (Workers 0 and 1 run 1 and 1, then Worker 0 runs 2), whereas sorting first would wrongly return 2.
  • Allocating all k workers blindly when n is tiny: Creating 10^5 heap entries for a 2-element list wastes time and memory, whereas min(k, len(durations)) keeps work proportional to actual tasks.
  • Using round-robin (task i -> worker i % k) or ceil(sum(durations) / k): Round-robin ignores task lengths and sends work to busy workers while others sit idle, and dividing the sum by k gives only a lower bound rather than the simulated finish time.

Alternative approaches

  • Fast-path check when k >= len(durations): Returning max(durations, default=0) directly takes O(n) time and O(1) extra space whenever workers outnumber tasks, though our O(n log h) heap already finishes well under any time limit for n <= 10^5.
  • Storing bare free_time integers without worker_id: Because all workers run at identical speed, breaking ties differently never changes the multiset of finish timestamps inside the heap, so makespan alone stays identical—still, storing (free_time, worker_id) follows the dispatch rules literally and extends cleanly to per-worker assignment tracking.

Follow-up questions

  • What changes are needed if each worker must report the sequence of task indices it executed rather than just the overall finish time? Initialize assigned = [[] for _ in range(k)], loop over enumerate(durations) to obtain (task_idx, duration), and append task_idx to assigned[worker_id] whenever (free_time, worker_id) is popped. Here the (free_time, worker_id) tie-breaker directly governs which worker list receives a tied task, while idle workers with worker_id >= min(k, len(durations)) simply retain []. Total time is O(n log h + k) and space is O(n + k).
  • How does the dispatch algorithm change when every task i carries an earliest start timestamp release[i]? Assuming tasks arrive in non-decreasing release order (release[0] <= release[1] <= ...), a popped worker starts task i at start_time = max(free_time, release[i]) and finishes at start_time + duration. That single adjustment computes the exact completion time because every worker already idle by release[i] starts at release[i] regardless of which one is picked. If strict lowest-worker_id tie-breaking among all workers idle at release[i] is also required, maintain two min-heaps—busy keyed by (free_time, worker_id) and idle keyed by worker_id—draining every worker with free_time <= release[i] into idle before assigning task i.
  • If you were allowed to reorder tasks freely beforehand to shrink the overall finish time, what greedy heuristic gives a provably near-optimal schedule? Computing the exact minimum finish time across parallel machines is NP-hard (a class of optimization problems with no known polynomial-time exact algorithm; even k = 2 contains the Partition problem). The classic Longest Processing Time first (LPT) rule sorts durations in descending order so long tasks start early and short tasks smooth out uneven tails at the end, then runs the same min-heap dispatch in O(n log n) time. Ronald Graham proved that LPT never exceeds (4/3 - 1/(3k)) times the true optimum, improving upon the (2 - 1/k) worst-case ratio of arbitrary order.

Follow-up questions

Similar questions

More Plaid interview questions

All 16 Plaid questions →