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 stage i (workers >= 1).
  • duration: how many time units a single worker at stage i spends 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:

  1. Wave execution inside a stage: When stage i runs a batch of B jobs, up to workers jobs run side by side in each wave, and every wave lasts duration time units. Processing B > 0 jobs at stage i therefore takes ceil(B / workers) * duration time units. An empty batch (B == 0) takes 0 time units.
  2. Full-batch handoff: Batch j cannot start stage i + 1 until every job in batch j has finished stage i.
  3. One batch per stage in arrival order: Each stage works on at most one batch at any moment, and stage i cannot begin batch j until stage i has completed batch j - 1.
  4. Concurrent stages: Separate stages may run different batches at the same time.
  5. All-or-nothing cutoff: All batches[j] jobs in batch j count toward the output if and only if batch j finishes the last stage (K - 1) at timestamp <= deadline. If batch j finishes after deadline, 0 of 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 (4 jobs): Stage 0 runs ceil(4 / 3) = 2 waves of 2 (t = 0 -> 4). Stage 1 starts at t = 4 and runs ceil(4 / 2) = 2 waves of 5 (t = 4 -> 14). Since 14 <= 27, all 4 jobs count.
  • Batch 1 (3 jobs): Stage 0 starts at t = 4 and runs ceil(3 / 3) = 1 wave of 2 (t = 4 -> 6). Stage 1 is still occupied by Batch 0 until t = 14, so Batch 1 starts Stage 1 at max(6, 14) = 14 and runs ceil(3 / 2) = 2 waves of 5 (t = 14 -> 24). Since 24 <= 27, all 3 jobs count.
  • Batch 2 (2 jobs): Stage 0 runs 1 wave (t = 6 -> 8), then Stage 1 starts at max(8, 24) = 24 and runs 1 wave (t = 24 -> 29). Since 29 > 27, Batch 2 misses the cutoff, leaving 4 + 3 = 7 completed jobs.

Example 2

stages = [(4, 3), (2, 2)]
batches = [0, 6]
deadline = 12
# Output: 6

Walk-through:

  • Batch 0 (0 jobs): Requires 0 waves at both stages, finishing at t = 0 <= 12 and contributing 0 jobs.
  • Batch 1 (6 jobs): Stage 0 runs ceil(6 / 4) = 2 waves of 3 (t = 0 -> 6), and Stage 1 runs ceil(6 / 2) = 3 waves of 2 (t = 6 -> 12). Finishing right on t = 12 == deadline counts, so the total is 6.

Constraints

  • 1 <= len(stages) <= 1,000
  • 1 <= stages[i][0] <= 10^6 (workers)
  • 0 <= stages[i][1] <= 10^6 (duration)
  • 0 <= len(batches) <= 10^4
  • 0 <= batches[j] <= 10^9
  • 0 <= deadline <= 10^18

Step-by-step walkthrough

  1. Understand the pipeline rules and the two waits

    We have K sequential pipeline stages stages[0..K-1] (each a (workers, duration) pair), N job batches batches[0..N-1] all arriving at t = 0, and an inclusive deadline (up to 10^18).

    A batch's jobs are counted all or nothing: if the batch finishes the last stage (K - 1) at or before deadline, we add all batches[j] jobs; otherwise we add 0.

    Every rule about how batches move boils down to two waits. Batch j can start at stage i only when both of these events have happened:

    1. Full-batch handoff: All jobs of batch j have finished stage i - 1 (at Stage 0, every batch is ready at t = 0).
    2. One batch per stage: Stage i has finished processing batch j - 1 (for Batch 0, every stage starts free at t = 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 0 can start Batch 1 while Stage 1 is busy with Batch 0).

  2. Compute wave time with exact integer ceiling

    Within stage i, workers parallel workers process up to workers jobs per wave, and each wave takes duration time units. For job_count jobs, we need ceil(job_count / workers) waves (0 waves if job_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 waves
    

    Why 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 to 2^53 (~9 * 10^15). Keeping every calculation in exact integers guarantees we never round a finish time across deadline.

  3. Turn the pipeline into a dynamic-programming grid

    Simulating a clock second by second is impossible when deadline can be 10^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_i
    

    with base boundaries finish(-1, j) = 0 (all batches arrive at t = 0) and finish(i, -1) = 0 (all stages start idle at t = 0).

    Picture a K x N table where rows are stages 0..K-1 and columns are batches 0..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)), taking O(1) work per cell—at most 1,000 * 10,000 = 10^7 simple arithmetic operations in total.

  4. 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 0 to K - 1), we never need to store the entire K x N grid in memory:

    • batch_ready_time holds the cell above (finish(i - 1, j)), starting at 0 for each new batch.
    • stage_free_time[i] holds the cell to the left (finish(i, j - 1)), and gets overwritten in place with finish(i, j) once the current batch finishes stage i.
    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_time
    

    After the inner loop finishes Stage K - 1, batch_ready_time is the exact timestamp when the current batch exits the pipeline, using only O(K) memory!

  5. 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, batch j cannot start until stage K - 1 finishes batch j - 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 after deadline (batch_ready_time > deadline), every subsequent batch will also finish strictly after deadline, so we can break immediately!

    Notice the strict > comparison: finishing at batch_ready_time == deadline counts as completed (as tested in Example 2, where Batch 1 finishes at t = 12 with deadline = 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.

  6. Trace Example 1 step by step

    Let us trace stages = [(3, 2), (2, 5)], batches = [4, 3, 2], and deadline = 27. Initially stage_free_time = [0, 0] and completed_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 0 at t = 8, it had to wait until t = 24 for Stage 1 to clear Batch 0 and Batch 1, pushing its completion to 29 > 27. The function returns 7.

  7. 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 (4 jobs): Stage 0 runs ceil(4 / 3) = 2 waves of 2s (0 -> 4); Stage 1 starts at max(4, 0) = 4 and runs ceil(4 / 2) = 2 waves of 5s (4 -> 14). Because 14 <= 27, all 4 jobs count (stage_free_time = [4, 14]).
  • Batch 1 (3 jobs): Stage 0 starts at max(0, 4) = 4 and runs 1 wave (4 -> 6); Stage 1 starts at max(6, 14) = 14 and runs ceil(3 / 2) = 2 waves (14 -> 24 <= 27), adding 3 more jobs (stage_free_time = [6, 24]).
  • Batch 2 (2 jobs): Stage 0 runs 1 wave (6 -> 8); Stage 1 starts at max(8, 24) = 24 and runs 1 wave (24 -> 29). Because 29 > 27, Batch 2 misses the cutoff, we stop early, and return 4 + 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 miss m, we loop across the K stages doing O(1) integer arithmetic per stage—at most 1,000 * 10,000 = 10^7 operations 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 list stage_free_time of length K rather than a full K x N table.

Edge cases

  • Empty batches ([]): The outer loop does not execute and returns 0.
  • Exact deadline match (finish_time == deadline): Counted as completed because we break only on strict batch_ready_time > deadline.
  • Empty batches (job_count = 0): (0 + workers - 1) // workers evaluates to 0 waves and 0 duration without a special branch, neither adding jobs nor delaying any later batch.
  • Zero-duration stages (duration = 0): waves * 0 = 0, so stages with duration = 0 advance instantly—even at deadline = 0, batches finish at t = 0 and 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^15 time units and deadline reaches 10^18. Pure integer math avoids floating-point rounding above 2^53, and breaking as soon as batch_ready_time > deadline keeps values bounded below 2^63 in 64-bit languages.

Common mistakes

  • Timing each batch independently (sum(waves * duration)): Ignores stage_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 of max(...): Stage i - 1 and Stage i run 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 // workers instead of ceiling division: Loses the partial last wave (for instance, 3 // 2 = 1 instead of 2 waves).
  • Breaking on >= deadline instead of > deadline: Drops batches that finish right on the deadline timestamp.
  • Counting partial jobs inside an unfinished batch: Batch completion is all-or-nothing; if a batch misses deadline at Stage K - 1, zero of its jobs count.

Alternative approaches

  • Stage-by-stage row traversal (O(N) space): You can keep an array of N finish times for Stage 0, then compute all N finish times for Stage 1, and so on up to Stage K - 1 (pruning the tail whenever timestamps exceed deadline). It performs the same O(K * N) arithmetic, but going batch by batch uses O(K) space (K <= 1,000 vs N <= 10,000) and stops immediately at the first batch whose final stage misses deadline.

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 + 1 the moment it finishes stage i rather than waiting for all batches[j] jobs to clear stage i. When total job count J = sum(batches) is moderate, track per-job exit timestamps across stages: at stage i with w workers, job n gets the worker freed by job n - w (while also waiting for stage i to finish batch j - 1 if exclusive stage occupancy still applies), running in O(K * J) time, and batch j completes when its last job exits stage K - 1. When batches[j] reaches 10^9, per-job simulation is infeasible, so we model large batches analytically using single-job pipeline latency sum(duration_i) plus the bottleneck stage throughput min(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 prefix 0..p - 1. You can therefore binary-search the number of completed batches p (0..N) and check whether the worker budget can make batch p - 1 finish by deadline. Notice that adding 1 worker often leaves ceil(B / workers) unchanged, so for small K or budget you only test worker jumps that actually reduce ceil(B / workers) for some batch in 0..p - 1; for larger inputs, a practical greedy heuristic repeatedly jumps whichever stage gives the largest finish-time reduction for batch p - 1 per 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 - 1 in arrival order, so the early-stop break is 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 to completed_jobs if stage_index == K - 1 and finish_time <= deadline) and immediately start the highest-priority waiting batch, running in O(K * N * (log N + log K)) total time.

Follow-up questions

Similar questions

More Plaid interview questions

All 16 Plaid questions →