Completed Tasks Across Sequential Stages

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

A single executor works through a linear sequence of n stages indexed 0 through n - 1. Stages are strictly gated in order: no task in stage i + 1 can start until every task in stage i has finished.

You receive two equal-length integer lists and a total time budget:

  • counts[i]: how many identical tasks belong to stage i.
  • durations[i]: time units needed to finish one task in stage i.
  • time_limit: total time units available before the clock expires.

A task counts toward the final total only if its entire durations[i] finishes at or before time_limit. As soon as a task would run past time_limit, that task does not count and the executor halts immediately without advancing to later stages.

Return the total number of tasks finished across all stages within time_limit, leaving both counts and durations unmodified.

def count_completed_jobs(counts: list[int], durations: list[int], time_limit: int) -> int:

Examples

Example 1

Input:  counts = [4, 3, 6], durations = [3, 8, 1], time_limit = 29
Output: 6

Walk-through: - Stage 0 runs 4 tasks at 3 units apiece (4 * 3 = 12 units), leaving 29 - 12 = 17 units on the clock. - Stage 1 requires 8 units per task. Within 17 remaining units, 17 // 8 = 2 tasks finish (16 units used, 1 left). The third task in Stage 1 needs 8 units and cannot finish, so Stage 1 stays incomplete and Stage 2 never opens. - Total finished tasks: 4 + 2 = 6.

Example 2

Input:  counts = [2, 0, 5, 4], durations = [3, 9, 0, 4], time_limit = 11
Output: 8

Walk-through: - Stage 0: 2 tasks taking 3 units each finish in 6 units, leaving 11 - 6 = 5 units. - Stage 1: contains 0 tasks, clearing right away and using 0 units (5 left). - Stage 2: contains 5 zero-duration tasks, so all 5 finish instantaneously (5 left). - Stage 3: each task needs 4 units, so 5 // 4 = 1 task finishes (1 unit left) before execution stops. - Total finished tasks: 2 + 0 + 5 + 1 = 8.

Constraints

  • n == len(counts) == len(durations)
  • 1 <= n <= 10^5
  • 0 <= counts[i] <= 10^9
  • 0 <= durations[i] <= 10^9
  • 0 <= time_limit <= 10^18
  • Input lists counts and durations must not be mutated.
  • In languages with fixed-width integers, stage products counts[i] * durations[i] can reach 10^18 and require 64-bit integer arithmetic.

Step-by-step walkthrough

  1. Understand the stage rules

    One executor advances through n stages numbered 0 through n - 1 in order. Stage i holds counts[i] identical tasks, each requiring durations[i] time units.

    Two strict rules govern execution:

    1. Sequential gate: Stage i + 1 stays locked until every task in stage i has finished.
    2. Hard cutoff: A task counts only when it finishes at or before time_limit. Once the next task cannot finish within the remaining budget, the executor stops immediately and later stages remain locked.
    Stage 0 (4 tasks x 3)        Stage 1 (3 tasks x 8)              Stage 2 (locked)
    [ 3 ][ 3 ][ 3 ][ 3 ] ------> [  8  ][  8  ][ 8 (cuts off!) ] --X--> never opens
    0    3    6    9   12        12     20     28    |
                                                time_limit = 29
    
    • Input: counts and durations of length n (up to 10^5, entries up to 10^9), plus time_limit (up to 10^18), without modifying either list.
    • Output: Total tasks finished across all stages.
  2. Why stepping one task at a time times out

    A direct job-by-job simulation tracks an elapsed clock and increments once per task:

    def count_by_simulation(counts: list[int], durations: list[int], time_limit: int) -> int:
        elapsed = 0
        completed = 0
        for job_count, job_duration in zip(counts, durations):
            for _ in range(job_count):
                if elapsed + job_duration > time_limit:
                    return completed
                elapsed += job_duration
                completed += 1
        return completed
    

    While great as a test oracle on tiny inputs, the inner loop runs once per task. With 10^5 stages and 10^9 tasks per stage, 10^14 iterations would run for hours.

  3. Settle an entire stage with one multiplication

    Because all tasks inside stage i take the exact same duration job_duration, we can compute the total time needed for the whole stage at once:

    stage_time = job_count * job_duration
    

    Compare stage_time against remaining_time:

    • Case 1 — Full stage fits (stage_time <= remaining_time): All job_count tasks finish. Add job_count to completed_jobs, subtract stage_time from remaining_time, and advance to the next stage.
    • Case 2 — Stage runs out of budget (stage_time > remaining_time): Use floor division (remaining_time // job_duration, dividing and rounding down to an integer) to count how many whole tasks finish before time expires, add that count, and break out of the loop because this stage never completes.

    Each stage now takes O(1) arithmetic, reducing total runtime to O(n). Python integers have arbitrary precision; in C++ or Java, job_count * job_duration reaches 10^18 and needs 64-bit integers (long long / long).

  4. Verify zero-count and zero-duration stages

    Empty stages (job_count == 0) and instant stages (job_duration == 0) are subtle when remaining_time has already hit 0. Because remaining_time starts at time_limit >= 0 and only decreases when stage_time <= remaining_time, remaining_time is always >= 0:

    Case              stage_time             Branch taken     Result
    ----------------  ---------------------  ---------------  ------------------------------------------
    job_count = 0     0 <= remaining_time    Full-stage (if)  Adds 0 tasks, remaining_time unchanged
    job_duration = 0  0 <= remaining_time    Full-stage (if)  Adds job_count instant tasks, time unchanged
    Partial stage     stage_time > remaining Else + break     Guarantees job_duration > 0, safe to divide!
    

    Checking stage_time <= remaining_time before dividing gives two critical guarantees:

    1. Instant stages at remaining_time == 0 still complete: When an earlier stage uses the last unit of budget (remaining_time == 0) and the next stage has job_duration == 0, 0 <= 0 holds, so all its zero-duration tasks finish right at time_limit.
    2. ZeroDivisionError can never happen: Entering else means job_count * job_duration > remaining_time >= 0. A product is strictly positive only when both factors are strictly positive, proving job_duration > 0 before remaining_time // job_duration runs.
  5. Code the single-pass stage loop

    def count_completed_jobs(counts: list[int], durations: list[int], time_limit: int) -> int:
        # remaining_time: int >= 0 tracking unused time units before time_limit
        remaining_time = time_limit
        # completed_jobs: int running total of fully finished jobs across stages
        completed_jobs = 0
    
        # Phase 1: Walk stages in strict 0 .. n-1 order because stage i+1 requires stage i to finish.
        for job_count, job_duration in zip(counts, durations):
            stage_time = job_count * job_duration
    
            # Use <= because jobs finishing right at time_limit count as completed.
            # This also handles job_count == 0 or job_duration == 0 (stage_time == 0 <= remaining_time).
            if stage_time <= remaining_time:
                completed_jobs += job_count
                remaining_time -= stage_time
            else:
                # Phase 2: Partial stage and pipeline stop.
                # Since job_count * job_duration > remaining_time >= 0, job_duration is strictly > 0
                # (so // cannot divide by zero) and remaining_time // job_duration is strictly < job_count.
                completed_jobs += remaining_time // job_duration
                break
    
        return completed_jobs
    
  6. Trace Example 1 and Example 2 step by step

    Example 1: counts = [4, 3, 6], durations = [3, 8, 1], time_limit = 29.

    Stage  job_count  job_duration  stage_time  remaining (before -> after)  completed_jobs
    -----  ---------  ------------  ----------  ---------------------------  --------------
      0        4            3           12      29 -> 17 (12 <= 29, full)    0 + 4 = 4
      1        3            8           24      17 (24 > 17, partial+break)  4 + (17 // 8) = 6
      2        6            1           --      never reached                6
    

    Output: 6.

    Example 2: counts = [2, 0, 5, 4], durations = [3, 9, 0, 4], time_limit = 11.

    Stage  job_count  job_duration  stage_time  remaining (before -> after)  completed_jobs
    -----  ---------  ------------  ----------  ---------------------------  --------------
      0        2            3            6      11 -> 5 (6 <= 11, full)      0 + 2 = 2
      1        0            9            0      5 -> 5 (0 <= 5, full)        2 + 0 = 2
      2        5            0            0      5 -> 5 (0 <= 5, full)        2 + 5 = 7
      3        4            4           16      5 (16 > 5, partial+break)    7 + (5 // 4) = 8
    

    Output: 8.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def count_completed_jobs(counts: list[int], durations: list[int], time_limit: int) -> int:
        # remaining_time: int >= 0 tracking unused time units before time_limit
        remaining_time = time_limit
        # completed_jobs: int running total of fully finished jobs across stages
        completed_jobs = 0
    
        # Phase 1: Walk stages in strict 0 .. n-1 order because stage i+1 requires stage i to finish.
        for job_count, job_duration in zip(counts, durations):
            stage_time = job_count * job_duration
    
            # Use <= because jobs finishing right at time_limit count as completed.
            # This also handles job_count == 0 or job_duration == 0 (stage_time == 0 <= remaining_time).
            if stage_time <= remaining_time:
                completed_jobs += job_count
                remaining_time -= stage_time
            else:
                # Phase 2: Partial stage and pipeline stop.
                # Since job_count * job_duration > remaining_time >= 0, job_duration is strictly > 0
                # (so // cannot divide by zero) and remaining_time // job_duration is strictly < job_count.
                completed_jobs += remaining_time // job_duration
                break
    
        return completed_jobs
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture an assembly-line technician on a countdown timer working through a row of sealed bins in strict sequence. Every part inside a single bin takes the exact same number of minutes to finish, and the next bin cannot be unsealed until the current bin is completely empty. Rather than timing each part individually, multiply the part count in the current bin by the minutes per part: when that total fits within the remaining timer, clear the whole bin in one step; otherwise use floor division (integer division //, which divides and rounds down to a whole number) to count how many complete parts finish before the timer runs out, and stop right there because later bins remain sealed.

Simulating one task at a time fails at scale because 10^5 stages holding up to 10^9 tasks each can total 10^14 tasks — hours of loop iterations. Resolving an entire stage with a single multiplication and at most one integer division turns each stage into O(1) arithmetic.

Tracing Example 1 (counts = [4, 3, 6], durations = [3, 8, 1], time_limit = 29):

  • Stage 0 (4 tasks of 3 units): Needs 4 * 3 = 12 units. Because 12 <= 29, all 4 finish (completed_jobs = 4) and remaining_time drops to 29 - 12 = 17.
  • Stage 1 (3 tasks of 8 units): Needs 3 * 8 = 24 units. Because 24 > 17, the stage cannot finish; 17 // 8 = 2 tasks complete (completed_jobs = 6), and execution halts before Stage 2 opens.

Complexity

  • Time: O(n), where n is the number of stages. Each stage performs one multiplication, one comparison, and at most one floor division before advancing or breaking early.
  • Space: O(1) auxiliary space. Only scalar integer variables (remaining_time, completed_jobs, stage_time) are stored while scanning the input lists without copying them.

Edge cases

  • time_limit == 0: Empty stages (counts[i] == 0) and zero-duration stages (durations[i] == 0) before the first positive-work stage satisfy 0 <= 0 and still complete.
  • Exact budget exhaustion followed by zero-duration tasks: If stage 0 brings remaining_time to 0 and stage 1 has durations[1] == 0, stage 1 still finishes right on the deadline (0 <= 0).
  • Incomplete stage followed by zero-duration tasks: Breaking on stage_time > remaining_time prevents any later free stages from being counted once an earlier stage stalls.
  • Empty stages (counts[i] == 0): Even when durations[i] == 10^9, 0 * 10^9 = 0 <= remaining_time passes cleanly using 0 time.
  • 64-bit numeric bounds: counts[i] * durations[i] reaches 10^18 and total completed tasks reach 10^14. Python integers never overflow, whereas C++ or Java require 64-bit signed integers (long long / long) to avoid integer overflow (wrapping past the ~2.1 * 10^9 ceiling of 32-bit signed ints).
  • Leftover budget: When time_limit exceeds total work across all stages, the loop finishes naturally and returns sum(counts).

Common mistakes

  • Dividing before testing stage_time <= remaining_time: Writing min(job_count, remaining_time // job_duration) raises ZeroDivisionError whenever job_duration == 0. Testing the product first guarantees job_duration > 0 inside else.
  • Stopping immediately when remaining_time == 0: Breaking right after an exact-fit stage skips subsequent zero-duration stages that legitimately complete at time_limit.
  • Using strict < instead of <=: Tasks finishing at time_limit (stage_time == remaining_time) count as completed.
  • Continuing past a stalled stage: Skipping an unfinished expensive stage to harvest cheap tasks in later stages violates the stage gate.

Follow-up questions

  • What changes if entering stage i requires paying a one-time warm-up cost before its first task can run? First confirm with the interviewer whether an empty stage (counts[i] == 0) bypasses warm-up or still incurs it; assuming warm-up applies whenever counts[i] > 0, check if warmup[i] > remaining_time: break at the top of stage i (even when durations[i] == 0, since warm-up precedes the first instant task). Otherwise deduct remaining_time -= warmup[i] and run the identical stage_time <= remaining_time vs remaining_time // job_duration check in O(1) time per stage.
  • Suppose k identical workers process the currently unlocked stage concurrently (while still waiting for all tasks in stage i to finish before stage i + 1 opens). How do you compute the total completed tasks? Because stage i starts at a synchronized barrier and all its tasks share duration job_duration, the k workers finish tasks in lockstep batches of k every job_duration units. Using ceiling division (dividing and rounding up via (job_count + k - 1) // k), clearing stage i requires batches = (job_count + k - 1) // k batches taking batches * job_duration time; when that exceeds remaining_time, remaining_time // job_duration full batches complete (remaining_time // job_duration) * k tasks (strictly fewer than job_count) before execution halts.
  • If the stage arrays never change and you receive q separate deadline queries, how can you preprocess the stages to answer each query in O(log n) time? Build two prefix sum arrays (cumulative totals over the first i stages) in O(n) preprocessing time: finish_time[i] storing cumulative time to clear stages 0 .. i - 1, and done_prefix[i] storing cumulative tasks across those stages. Because finish_time is monotonically non-decreasing, run binary search (bisect_right(finish_time, deadline) - 1, repeatedly halving the search interval) to locate the index m of the first stage not completely cleared by deadline — which automatically advances past trailing zero-time stages. When m == n, return done_prefix[n]; otherwise finish_time[m + 1] > deadline >= finish_time[m] implies durations[m] > 0, so return done_prefix[m] + (deadline - finish_time[m]) // durations[m] in O(log n) time per query.

Follow-up questions

Similar questions

More Plaid interview questions

All 16 Plaid questions →