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, then1, then2, 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 untils + durations[i](a task withdurations[i] == 0completes instantaneously ats, leaving that node idle ats).
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^51 <= k <= 10^50 <= durations[i] <= 10^9- Total completion time can reach
10^{14}, so 64-bit (or arbitrary-precision) integer arithmetic is required (durations == []returns0)
Step-by-step walkthrough
Understand the problem and dispatch rules
We receive
durations(up to10^5non-negative task lengths in arrival order) andk(up to10^5identical parallel workers numbered0throughk - 1, all initially idle att = 0).Our goal is to find the overall makespan: how much time passes from
t = 0until the very last task finishes (0whendurationsis empty).Notice that reordering tasks is not permitted—the dispatch sequence is completely fixed:
- Process tasks strictly in arrival order: index
0, then1, and so on. - Route each task to whichever worker has the smallest
free_time. - Whenever several workers share the same
free_time, pick the worker with the smallestworker_id. - Once chosen, that worker stays busy from
free_timeuntilfree_time + duration.
Because
10^5tasks can each run for10^9seconds on a single worker, the total finish time can reach10^14, overflowing 32-bit signed integers (~2.1 * 10^9) in C++ or Java; Python integers expand to arbitrary precision automatically.- Process tasks strictly in arrival order: index
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^9seconds, and total runtime can hit10^14seconds—far too many ticks to loop through. - Scanning an array
free[0..k-1]on every task: Inspecting allkworkers for each of thentasks costsO(n * k)work. Atn = 10^5andk = 10^5, that reaches10^10comparisons.
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.- Advancing a clock one second at a time: A single task can span
Key idea: A min-heap of `(free_time, worker_id)` tuples
A min-heap (provided by Python's
heapqmodule) is a binary tree packed into a list that keeps its smallest item at index0, letting us pop the minimum and push an updated entry inO(log h)time (forhheap entries).Representing each worker as the 2-tuple
(free_time, worker_id)makes Python's tuple comparison handle both rules automatically:- Compare
free_timefirst (smaller timestamp wins — earliest-idle worker). - Break equal
free_timeties byworker_id(smaller index wins).
One extra observation shrinks the heap whenever
kvastly exceedslen(durations)(say3tasks andk = 100,000): att = 0, task0claims worker0, task1claims worker1, and task2claims worker2. Workers3..99,999will never be touched! Capping the pool atworker_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, soworkersalready satisfies the binary min-heap invariant without callingheapq.heapify().- Compare
Dispatch each task and track the running maximum finish time
For each
durationindurations, pop(free_time, worker_id), computefinish_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 indurations? Consider Example 3 (durations = [11, 0, 4, 3]withk = 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
3is dispatched last, yet it finishes att = 7on Worker1while Worker0is still busy with task0untilt = 11. Maintaining the running maximum captures11cleanly. Also notice task1(0s):finish_time = 0 + 0 = 0, so pushing(0, 1)puts Worker1right back at the top of the heap att = 0.Trace Example 1 step by step
Let us trace
durations = [4, 2, 5, 3, 6]withk = 2. Initiallyworkers = [(0, 0), (0, 1)]andmakespan = 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)] | 13At
t = 7,(7, 0) < (7, 1)breaks the tie in favor of Worker0, and all five tasks complete byt = 13.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 at4, pushes(4, 0);makespan = 4. - Task
1(2s) pops(0, 1)-> finishes at2, pushes(2, 1);makespan = 4. - Task
2(5s) pops(2, 1)-> finishes at7, pushes(7, 1);makespan = 7. - Task
3(3s) pops(4, 0)-> finishes at7, pushes(7, 0);makespan = 7. - Task
4(6s) pops(7, 0)(tie at7goes to worker0) -> finishes at13, pushes(13, 0);makespan = 13.
Complexity
Let n = len(durations) and h = min(k, n).
- Time —
O(n log h): Building thehinitial(0, worker_id)entries in ascending order takesO(h)time, and each of thentasks runs oneheappopand oneheappushon a heap of sizeh, costingO(log h)per task. - Space —
O(h): The heap holds at mostmin(k, n)(free_time, worker_id)tuples at any point, so even whenk = 100,000andn = 3, only 3 tuples are allocated.
Edge cases
- Empty
durations([]): Handled up front byif not durations: return 0. - More workers than tasks (
k >= n): Onlynworkers are created atfree_time = 0, every task starts att = 0, andmakespanequalsmax(durations). - Single worker (
k = 1): The heap has size1, tasks run back to back, andmakespanequalssum(durations). - Zero-duration tasks (
duration = 0):finish_time = free_time + 0pushes(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)comparesworker_idwheneverfree_timeties, always picking the lowest worker index. - 64-bit integer overflow:
10^5tasks of length10^9onk = 1worker reach10^14, exceeding 32-bit signed integers (2^31 - 1); Python handles arbitrary-precision integers natively, whereas C++/Java requireint64_t/long.
Common mistakes
- Returning the finish time of the final task in
durations: In Example 3 ([11, 0, 4, 3]withk = 2), the final task finishes att = 7on Worker1while Worker0continues running task0untilt = 11. Always maintainmax(makespan, finish_time). - Sorting
durationsbefore dispatching: Tasks must be dispatched strictly in arrival order; on[1, 1, 2]withk = 2, arrival order yields3(Workers0and1run1and1, then Worker0runs2), whereas sorting first would wrongly return2. - Allocating all
kworkers blindly whennis tiny: Creating10^5heap entries for a 2-element list wastes time and memory, whereasmin(k, len(durations))keeps work proportional to actual tasks. - Using round-robin (
task i -> worker i % k) orceil(sum(durations) / k): Round-robin ignores task lengths and sends work to busy workers while others sit idle, and dividing the sum bykgives only a lower bound rather than the simulated finish time.
Alternative approaches
- Fast-path check when
k >= len(durations): Returningmax(durations, default=0)directly takesO(n)time andO(1)extra space whenever workers outnumber tasks, though ourO(n log h)heap already finishes well under any time limit forn <= 10^5. - Storing bare
free_timeintegers withoutworker_id: Because all workers run at identical speed, breaking ties differently never changes the multiset of finish timestamps inside the heap, somakespanalone 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 overenumerate(durations)to obtain(task_idx, duration), and appendtask_idxtoassigned[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 withworker_id >= min(k, len(durations))simply retain[]. Total time isO(n log h + k)and space isO(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 taskiatstart_time = max(free_time, release[i])and finishes atstart_time + duration. That single adjustment computes the exact completion time because every worker already idle byrelease[i]starts atrelease[i]regardless of which one is picked. If strict lowest-worker_idtie-breaking among all workers idle atrelease[i]is also required, maintain two min-heaps—busykeyed by(free_time, worker_id)andidlekeyed byworker_id—draining every worker withfree_time <= release[i]intoidlebefore assigning taski. - 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 = 2contains the Partition problem). The classic Longest Processing Time first (LPT) rule sortsdurationsin descending order so long tasks start early and short tasks smooth out uneven tails at the end, then runs the same min-heap dispatch inO(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
- What changes are needed if each worker must report the sequence of task indices it executed rather than just the overall finish time?
- How does the dispatch algorithm change when every task i carries an earliest start timestamp release[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?
Similar questions
- Sequential Queue Discounts and Total Savings
- Batch Job Throughput in a Multi-Stage Worker Pipeline
- Completed Tasks Across Sequential Stages
- In-Memory Promo Code Redemption Service
- Consolidate Bank Routing Mappings Across Data Feeds
- Verifying All-Pass Chained Rule Delegations
More Plaid interview questions
- Completed Tasks Across Sequential Stages Medium
- Batch Job Throughput in a Multi-Stage Worker Pipeline Medium
- Design a Streaming Conversational AI Service Easy Pro
- In-Memory Promo Code Redemption Service Medium Pro
- Globally Coordinated Multi-Region Rate Limiter Easy Pro
- Consolidate Bank Routing Mappings Across Data Feeds Easy Pro
- Resolving Chained Boolean Rule Expressions Medium Pro
- Verifying All-Pass Chained Rule Delegations Medium Pro
- Sequential Queue Discounts and Total Savings Medium Pro
- Enterprise RAG Evaluation, Monitoring, and Triage Medium Pro