Batch Job Throughput in a Multi-Stage Worker Pipeline
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A batch-processing workflow passes work through K ordered stages numbered 0 to K - 1. Stage i is described by stages[i] = (workers, duration):
workers: how many identical workers operate in parallel at stagei(workers >= 1).duration: how many time units a single worker at stageispends on one job (duration >= 0).
At timestamp t = 0, an ordered list of job groups batches arrives in front of stage 0, where batches[j] gives the number of jobs inside batch j.
Execution obeys five scheduling rules:
- Wave execution inside a stage: When stage
iruns a batch ofBjobs, up toworkersjobs run side by side in each wave, and every wave lastsdurationtime units. ProcessingB > 0jobs at stageitherefore takesceil(B / workers) * durationtime units. An empty batch (B == 0) takes0time units. - Full-batch handoff: Batch
jcannot start stagei + 1until every job in batchjhas finished stagei. - One batch per stage in arrival order: Each stage works on at most one batch at any moment, and stage
icannot begin batchjuntil stageihas completed batchj - 1. - Concurrent stages: Separate stages may run different batches at the same time.
- All-or-nothing cutoff: All
batches[j]jobs in batchjcount toward the output if and only if batchjfinishes the last stage (K - 1) at timestamp<= deadline. If batchjfinishes afterdeadline,0of its jobs count.
Implement count_completed_jobs(stages, batches, deadline) to return the total number of jobs across all batches that complete stage K - 1 at or before deadline.
def count_completed_jobs(stages: List[Tuple[int, int]], batches: List[int], deadline: int) -> int:
pass
Examples
Example 1
stages = [(3, 2), (2, 5)]
batches = [4, 3, 2]
deadline = 27
# Output: 7
Walk-through:
- Batch 0 (
4jobs): Stage0runsceil(4 / 3) = 2waves of2(t = 0 -> 4). Stage1starts att = 4and runsceil(4 / 2) = 2waves of5(t = 4 -> 14). Since14 <= 27, all4jobs count. - Batch 1 (
3jobs): Stage0starts att = 4and runsceil(3 / 3) = 1wave of2(t = 4 -> 6). Stage1is still occupied by Batch0untilt = 14, so Batch1starts Stage1atmax(6, 14) = 14and runsceil(3 / 2) = 2waves of5(t = 14 -> 24). Since24 <= 27, all3jobs count. - Batch 2 (
2jobs): Stage0runs1wave (t = 6 -> 8), then Stage1starts atmax(8, 24) = 24and runs1wave (t = 24 -> 29). Since29 > 27, Batch2misses the cutoff, leaving4 + 3 = 7completed jobs.
Example 2
stages = [(4, 3), (2, 2)]
batches = [0, 6]
deadline = 12
# Output: 6
Walk-through:
- Batch 0 (
0jobs): Requires0waves at both stages, finishing att = 0 <= 12and contributing0jobs. - Batch 1 (
6jobs): Stage0runsceil(6 / 4) = 2waves of3(t = 0 -> 6), and Stage1runsceil(6 / 2) = 3waves of2(t = 6 -> 12). Finishing right ont = 12 == deadlinecounts, so the total is6.
Constraints
1 <= len(stages) <= 1,0001 <= stages[i][0] <= 10^6(workers)0 <= stages[i][1] <= 10^6(duration)0 <= len(batches) <= 10^40 <= batches[j] <= 10^90 <= deadline <= 10^18
Step-by-step walkthrough
Understand the pipeline rules and the two waits
We have
Ksequential pipeline stagesstages[0..K-1](each a(workers, duration)pair),Njob batchesbatches[0..N-1]all arriving att = 0, and an inclusivedeadline(up to10^18).A batch's jobs are counted all or nothing: if the batch finishes the last stage (
K - 1) at or beforedeadline, we add allbatches[j]jobs; otherwise we add0.Every rule about how batches move boils down to two waits. Batch
jcan start at stageionly when both of these events have happened:- Full-batch handoff: All jobs of batch
jhave finished stagei - 1(at Stage0, every batch is ready att = 0). - One batch per stage: Stage
ihas finished processing batchj - 1(for Batch0, every stage starts free att = 0).
Batch j finished Stage i - 1 | v Stage i: [ Batch j - 1 ] ---> start(i, j) = max(finish(i - 1, j), finish(i, j - 1)) (stage frees up)Meanwhile, different stages can work on different batches simultaneously (Stage
0can start Batch1while Stage1is busy with Batch0).- Full-batch handoff: All jobs of batch
Compute wave time with exact integer ceiling
Within stage
i,workersparallel workers process up toworkersjobs per wave, and each wave takesdurationtime units. Forjob_countjobs, we needceil(job_count / workers)waves (0waves ifjob_count == 0).We can compute
ceil(job_count / workers)using pure integer floor division:waves = (job_count + workers - 1) // workers Check with workers = 3: job_count = 0 -> (0 + 2) // 3 = 0 waves (empty batch takes 0 time automatically!) job_count = 1 -> (1 + 2) // 3 = 1 wave job_count = 3 -> (3 + 2) // 3 = 1 wave job_count = 4 -> (4 + 2) // 3 = 2 wavesWhy avoid floating-point arithmetic anywhere in our timing math? Finish times can exceed
10^18, whereas 64-bit IEEE floats only represent every integer exactly up to2^53(~9 * 10^15). Keeping every calculation in exact integers guarantees we never round a finish time acrossdeadline.Turn the pipeline into a dynamic-programming grid
Simulating a clock second by second is impossible when
deadlinecan be10^18. Instead, we jump directly to each batch's start and finish timestamps at each stage using the two waits from Step 1:start(i, j) = max(finish(i - 1, j), finish(i, j - 1)) finish(i, j) = start(i, j) + waves(i, j) * duration_iwith base boundaries
finish(-1, j) = 0(all batches arrive att = 0) andfinish(i, -1) = 0(all stages start idle att = 0).Picture a
K x Ntable where rows are stages0..K-1and columns are batches0..N-1:Batch 0 Batch 1 Batch 2 Stage 0: [fin(0,0)] -> [fin(0,1)] -> [fin(0,2)] | | | v v v Stage 1: [fin(1,0)] -> [fin(1,1)] -> [fin(1,2)]Each cell
(i, j)depends only on the cell above it (finish(i - 1, j)) and the cell to its left (finish(i, j - 1)), takingO(1)work per cell—at most1,000 * 10,000 = 10^7simple arithmetic operations in total.Compress the grid to a single 1D array of stage free times
If we fill the table column by column (one batch at a time, walking down through stages
0toK - 1), we never need to store the entireK x Ngrid in memory:batch_ready_timeholds the cell above (finish(i - 1, j)), starting at0for each new batch.stage_free_time[i]holds the cell to the left (finish(i, j - 1)), and gets overwritten in place withfinish(i, j)once the current batch finishes stagei.
from typing import List, Tuple def trace_batches(stages: List[Tuple[int, int]], batches: List[int]) -> List[int]: stage_free_time: List[int] = [0] * len(stages) for job_count in batches: batch_ready_time = 0 for stage_index in range(len(stages)): workers, duration = stages[stage_index] waves = (job_count + workers - 1) // workers start_time = max(batch_ready_time, stage_free_time[stage_index]) finish_time = start_time + waves * duration batch_ready_time = finish_time stage_free_time[stage_index] = finish_time return stage_free_timeAfter the inner loop finishes Stage
K - 1,batch_ready_timeis the exact timestamp when the current batch exits the pipeline, using onlyO(K)memory!Enforce the inclusive deadline and stop early
Can a small later batch ever sneak past a slow earlier batch and finish before
deadline? Never.At the final stage
K - 1, batchjcannot start until stageK - 1finishes batchj - 1:finish(K - 1, j) >= start(K - 1, j) >= finish(K - 1, j - 1)Because
waves * duration >= 0, final-stage completion times are monotonically non-decreasing across batches. As soon as one batch finishes strictly afterdeadline(batch_ready_time > deadline), every subsequent batch will also finish strictly afterdeadline, so we canbreakimmediately!Notice the strict
>comparison: finishing atbatch_ready_time == deadlinecounts as completed (as tested in Example 2, where Batch 1 finishes att = 12withdeadline = 12). In fixed-width 64-bit languages like C++ or Java, breaking early also prevents integer overflow on huge late batches, keeping intermediate values at or below~2 * 10^18 < 2^63 - 1.Trace Example 1 step by step
Let us trace
stages = [(3, 2), (2, 5)],batches = [4, 3, 2], anddeadline = 27. Initiallystage_free_time = [0, 0]andcompleted_jobs = 0:Timeline: Time: 0 4 6 8 14 24 27 29 Stage 0: [=B0=][B1][B2] Stage 1: [=== Batch 0 ===][=== Batch 1 ===][=B2=] ^ ^ ^ ^ t=14 t=24 cutoff t=29 (missed!) Step-by-step state: Batch 0 (job_count = 4): Stage 0 (w=3, d=2): waves = ceil(4/3) = 2, start = max(0, 0) = 0, finish = 0 + 4 = 4 stage_free_time -> [4, 0] Stage 1 (w=2, d=5): waves = ceil(4/2) = 2, start = max(4, 0) = 4, finish = 4 + 10 = 14 stage_free_time -> [4, 14] Check deadline: 14 <= 27 -> completed_jobs = 0 + 4 = 4 Batch 1 (job_count = 3): Stage 0 (w=3, d=2): waves = ceil(3/3) = 1, start = max(0, 4) = 4, finish = 4 + 2 = 6 stage_free_time -> [6, 14] Stage 1 (w=2, d=5): waves = ceil(3/2) = 2, start = max(6, 14) = 14, finish = 14 + 10 = 24 stage_free_time -> [6, 24] Check deadline: 24 <= 27 -> completed_jobs = 4 + 3 = 7 Batch 2 (job_count = 2): Stage 0 (w=3, d=2): waves = ceil(2/3) = 1, start = max(0, 6) = 6, finish = 6 + 2 = 8 stage_free_time -> [8, 24] Stage 1 (w=2, d=5): waves = ceil(2/2) = 1, start = max(8, 24) = 24, finish = 24 + 5 = 29 stage_free_time -> [8, 29] Check deadline: 29 > 27 -> break!Even though Batch 2 cleared Stage
0att = 8, it had to wait untilt = 24for Stage1to clear Batch0and Batch1, pushing its completion to29 > 27. The function returns7.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def count_completed_jobs(stages: List[Tuple[int, int]], batches: List[int], deadline: int) -> int: # stage_free_time[i]: timestamp when stage i finished the previous batch. # Example for 2 stages after Batch 0: [4, 14] means Stage 0 frees at 4, Stage 1 at 14. stage_free_time: List[int] = [0] * len(stages) completed_jobs = 0 # Phase 1: push batches through all K stages in submission order. for job_count in batches: # batch_ready_time: when the current batch cleared the preceding stage (0 before Stage 0). batch_ready_time = 0 for stage_index in range(len(stages)): workers, duration = stages[stage_index] # Exact integer ceiling ceil(job_count / workers); yields 0 waves when job_count == 0 # and avoids float precision loss when timestamps exceed 2^53 (~9 * 10^15). waves = (job_count + workers - 1) // workers stage_duration = waves * duration # Synchronization rule: wait for BOTH the batch barrier from stage i - 1 # AND for stage i to finish the previous batch j - 1. start_time = max(batch_ready_time, stage_free_time[stage_index]) finish_time = start_time + stage_duration batch_ready_time = finish_time stage_free_time[stage_index] = finish_time # Phase 2: check the inclusive deadline (finish_time <= deadline counts). # Because start_time >= stage_free_time[K - 1], final-stage finish times never # decrease from batch to batch, so no later batch can finish by the deadline either. if batch_ready_time > deadline: break completed_jobs += job_count return completed_jobs✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a commercial laundry assembly line (Wash -> Dry) handling numbered baskets of clothes (batches). Each station can work on only one basket at a time (washing or drying items in parallel waves up to its machine count), and an entire basket must finish washing before any item in it can enter the dryers—a rule called barrier synchronization (requiring every item in a group to finish the current stage before any item advances to the next stage). Meanwhile, the washers can immediately start washing Basket 1 while the dryers are busy drying Basket 0.
Ticking a clock one unit at a time fails completely because deadline can reach 10^18, and timing each batch in isolation fails because a fast second batch still gets stuck waiting behind a slow first batch at busy downstream stages. Instead, we use dynamic programming (computing each step's answer directly from previously computed answers): batch j starts stage i at max(batch_ready_time, stage_free_time[i]), waiting for whichever finishes later—the current batch clearing stage i - 1, or stage i clearing batch j - 1.
Let us trace Example 1 with stages = [(3, 2), (2, 5)], batches = [4, 3, 2], and deadline = 27:
- Batch 0 (
4jobs): Stage0runsceil(4 / 3) = 2waves of2s(0 -> 4); Stage1starts atmax(4, 0) = 4and runsceil(4 / 2) = 2waves of5s(4 -> 14). Because14 <= 27, all4jobs count (stage_free_time = [4, 14]). - Batch 1 (
3jobs): Stage0starts atmax(0, 4) = 4and runs1wave (4 -> 6); Stage1starts atmax(6, 14) = 14and runsceil(3 / 2) = 2waves (14 -> 24 <= 27), adding3more jobs (stage_free_time = [6, 24]). - Batch 2 (
2jobs): Stage0runs1wave (6 -> 8); Stage1starts atmax(8, 24) = 24and runs1wave (24 -> 29). Because29 > 27, Batch 2 misses the cutoff, we stop early, and return4 + 3 = 7.
Complexity
Let K = len(stages) and N = len(batches).
- Time —
O(K * N)worst case (O(K * m)with early exit): For each batch up to the first deadline missm, we loop across theKstages doingO(1)integer arithmetic per stage—at most1,000 * 10,000 = 10^7operations when every batch finishes on time. - Space —
O(K): Because we process one batch end-to-end across all stages before moving to the next batch, we only store the 1D liststage_free_timeof lengthKrather than a fullK x Ntable.
Edge cases
- Empty
batches([]): The outer loop does not execute and returns0. - Exact deadline match (
finish_time == deadline): Counted as completed because we break only on strictbatch_ready_time > deadline. - Empty batches (
job_count = 0):(0 + workers - 1) // workersevaluates to0waves and0duration without a special branch, neither adding jobs nor delaying any later batch. - Zero-duration stages (
duration = 0):waves * 0 = 0, so stages withduration = 0advance instantly—even atdeadline = 0, batches finish att = 0and count. - Small batch behind a huge batch: Even a 1-job batch cannot overtake an earlier slow batch at any stage, so breaking at the first missed deadline never skips a valid later batch.
- Large 64-bit timestamps: A single stage can take
10^9 * 10^6 = 10^15time units anddeadlinereaches10^18. Pure integer math avoids floating-point rounding above2^53, and breaking as soon asbatch_ready_time > deadlinekeeps values bounded below2^63in 64-bit languages.
Common mistakes
- Timing each batch independently (
sum(waves * duration)): Ignoresstage_free_time[i], falsely assuming downstream stages are always idle when the next batch arrives. - Adding the two waits (
batch_ready_time + stage_free_time[i]) instead ofmax(...): Stagei - 1and Stageirun in parallel on consecutive batches, so the batch waits until both prerequisites finish—the maximum of the two timestamps, not their sum. - Using floor division
job_count // workersinstead of ceiling division: Loses the partial last wave (for instance,3 // 2 = 1instead of2waves). - Breaking on
>= deadlineinstead of> deadline: Drops batches that finish right on thedeadlinetimestamp. - Counting partial jobs inside an unfinished batch: Batch completion is all-or-nothing; if a batch misses
deadlineat StageK - 1, zero of its jobs count.
Alternative approaches
- Stage-by-stage row traversal (
O(N)space): You can keep an array ofNfinish times for Stage0, then compute allNfinish times for Stage1, and so on up to StageK - 1(pruning the tail whenever timestamps exceeddeadline). It performs the sameO(K * N)arithmetic, but going batch by batch usesO(K)space (K <= 1,000vsN <= 10,000) and stops immediately at the first batch whose final stage missesdeadline.
Follow-up questions
- How does the calculation change if single jobs can advance to the next stage as soon as they finish, removing the full-batch barrier? Without the full-batch handoff, an individual job can enter stage
i + 1the moment it finishes stageirather than waiting for allbatches[j]jobs to clear stagei. When total job countJ = sum(batches)is moderate, track per-job exit timestamps across stages: at stageiwithwworkers, jobngets the worker freed by jobn - w(while also waiting for stageito finish batchj - 1if exclusive stage occupancy still applies), running inO(K * J)time, and batchjcompletes when its last job exits stageK - 1. Whenbatches[j]reaches10^9, per-job simulation is infeasible, so we model large batches analytically using single-job pipeline latencysum(duration_i)plus the bottleneck stage throughputmin(workers_i / duration_i). - Given a fixed budget of extra workers to distribute across stages, how would you choose where to place them to maximize finished jobs by the cutoff? Adding workers can only decrease or preserve
ceil(B / workers)at every stage, which monotonically lowers or preserves every batch's finish time, and completed batches always form a prefix0..p - 1. You can therefore binary-search the number of completed batchesp(0..N) and check whether the worker budget can make batchp - 1finish bydeadline. Notice that adding 1 worker often leavesceil(B / workers)unchanged, so for smallKor budget you only test worker jumps that actually reduceceil(B / workers)for some batch in0..p - 1; for larger inputs, a practical greedy heuristic repeatedly jumps whichever stage gives the largest finish-time reduction for batchp - 1per extra worker spent. - How would you redesign the simulation if each batch carried a priority score and higher-priority waiting batches jumped ahead at stage handoffs? Because higher-priority batches can overtake lower-priority ones while waiting between stages (without interrupting a batch already running inside a stage), batches no longer exit Stage
K - 1in arrival order, so the early-stopbreakis no longer valid. Instead, run a discrete-event simulation using a min-heap of(finish_time, stage_index)completion events alongside a per-stage priority queue of waiting batches ordered by(-priority, batch_index). Whenever a stage finishes a batch, push that batch into the next stage's waiting queue (or add its jobs tocompleted_jobsifstage_index == K - 1andfinish_time <= deadline) and immediately start the highest-priority waiting batch, running inO(K * N * (log N + log K))total time.
Follow-up questions
- How does the calculation change if single jobs can advance to the next stage as soon as they finish, removing the full-batch barrier?
- Given a fixed budget of extra workers to distribute across stages, how would you choose where to place them to maximize finished jobs by the cutoff?
- How would you redesign the simulation if each batch carried a priority score and higher-priority waiting batches jumped ahead at stage handoffs?
Similar questions
- Total Runtime of Queued Tasks Across Workers
- Sequential Queue Discounts and Total Savings
- 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
- Total Runtime of Queued Tasks Across Workers 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