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 stagei.durations[i]: time units needed to finish one task in stagei.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^50 <= counts[i] <= 10^90 <= durations[i] <= 10^90 <= time_limit <= 10^18- Input lists
countsanddurationsmust not be mutated. - In languages with fixed-width integers, stage products
counts[i] * durations[i]can reach10^18and require 64-bit integer arithmetic.
Step-by-step walkthrough
Understand the stage rules
One executor advances through
nstages numbered0throughn - 1in order. Stageiholdscounts[i]identical tasks, each requiringdurations[i]time units.Two strict rules govern execution:
- Sequential gate: Stage
i + 1stays locked until every task in stageihas finished. - 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:
countsanddurationsof lengthn(up to10^5, entries up to10^9), plustime_limit(up to10^18), without modifying either list. - Output: Total tasks finished across all stages.
- Sequential gate: Stage
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 completedWhile great as a test oracle on tiny inputs, the inner loop runs once per task. With
10^5stages and10^9tasks per stage,10^14iterations would run for hours.Settle an entire stage with one multiplication
Because all tasks inside stage
itake the exact same durationjob_duration, we can compute the total time needed for the whole stage at once:stage_time = job_count * job_durationCompare
stage_timeagainstremaining_time:- Case 1 — Full stage fits (
stage_time <= remaining_time): Alljob_counttasks finish. Addjob_counttocompleted_jobs, subtractstage_timefromremaining_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, andbreakout of the loop because this stage never completes.
Each stage now takes
O(1)arithmetic, reducing total runtime toO(n). Python integers have arbitrary precision; in C++ or Java,job_count * job_durationreaches10^18and needs 64-bit integers (long long/long).- Case 1 — Full stage fits (
Verify zero-count and zero-duration stages
Empty stages (
job_count == 0) and instant stages (job_duration == 0) are subtle whenremaining_timehas already hit0. Becauseremaining_timestarts attime_limit >= 0and only decreases whenstage_time <= remaining_time,remaining_timeis 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_timebefore dividing gives two critical guarantees:- Instant stages at
remaining_time == 0still complete: When an earlier stage uses the last unit of budget (remaining_time == 0) and the next stage hasjob_duration == 0,0 <= 0holds, so all its zero-duration tasks finish right attime_limit. ZeroDivisionErrorcan never happen: Enteringelsemeansjob_count * job_duration > remaining_time >= 0. A product is strictly positive only when both factors are strictly positive, provingjob_duration > 0beforeremaining_time // job_durationruns.
- Instant stages at
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_jobsTrace 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 6Output:
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) = 8Output:
8.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 (
4tasks of3units): Needs4 * 3 = 12units. Because12 <= 29, all4finish (completed_jobs = 4) andremaining_timedrops to29 - 12 = 17. - Stage 1 (
3tasks of8units): Needs3 * 8 = 24units. Because24 > 17, the stage cannot finish;17 // 8 = 2tasks complete (completed_jobs = 6), and execution halts before Stage 2 opens.
Complexity
- Time: O(n), where
nis 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 satisfy0 <= 0and still complete.- Exact budget exhaustion followed by zero-duration tasks: If stage
0bringsremaining_timeto0and stage1hasdurations[1] == 0, stage1still finishes right on the deadline (0 <= 0). - Incomplete stage followed by zero-duration tasks: Breaking on
stage_time > remaining_timeprevents any later free stages from being counted once an earlier stage stalls. - Empty stages (
counts[i] == 0): Even whendurations[i] == 10^9,0 * 10^9 = 0 <= remaining_timepasses cleanly using0time. - 64-bit numeric bounds:
counts[i] * durations[i]reaches10^18and total completed tasks reach10^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^9ceiling of 32-bit signed ints). - Leftover budget: When
time_limitexceeds total work across all stages, the loop finishes naturally and returnssum(counts).
Common mistakes
- Dividing before testing
stage_time <= remaining_time: Writingmin(job_count, remaining_time // job_duration)raisesZeroDivisionErrorwheneverjob_duration == 0. Testing the product first guaranteesjob_duration > 0insideelse. - Stopping immediately when
remaining_time == 0: Breaking right after an exact-fit stage skips subsequent zero-duration stages that legitimately complete attime_limit. - Using strict
<instead of<=: Tasks finishing attime_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 whenevercounts[i] > 0, checkif warmup[i] > remaining_time: breakat the top of stagei(even whendurations[i] == 0, since warm-up precedes the first instant task). Otherwise deductremaining_time -= warmup[i]and run the identicalstage_time <= remaining_timevsremaining_time // job_durationcheck inO(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
istarts at a synchronized barrier and all its tasks share durationjob_duration, thekworkers finish tasks in lockstep batches ofkeveryjob_durationunits. Using ceiling division (dividing and rounding up via(job_count + k - 1) // k), clearing stageirequiresbatches = (job_count + k - 1) // kbatches takingbatches * job_durationtime; when that exceedsremaining_time,remaining_time // job_durationfull batches complete(remaining_time // job_duration) * ktasks (strictly fewer thanjob_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
istages) inO(n)preprocessing time:finish_time[i]storing cumulative time to clear stages0 .. i - 1, anddone_prefix[i]storing cumulative tasks across those stages. Becausefinish_timeis monotonically non-decreasing, run binary search (bisect_right(finish_time, deadline) - 1, repeatedly halving the search interval) to locate the indexmof the first stage not completely cleared bydeadline— which automatically advances past trailing zero-time stages. Whenm == n, returndone_prefix[n]; otherwisefinish_time[m + 1] > deadline >= finish_time[m]impliesdurations[m] > 0, so returndone_prefix[m] + (deadline - finish_time[m]) // durations[m]inO(log n)time per query.
Follow-up questions
- What changes if entering stage i requires paying a one-time warm-up cost before its first task can run?
- 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?
- 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?
Similar questions
- Total Runtime of Queued Tasks Across Workers
- Sequential Queue Discounts and Total Savings
- Batch Job Throughput in a Multi-Stage Worker Pipeline
- In-Memory Promo Code Redemption Service
- Consolidate Bank Routing Mappings Across Data Feeds
- Verifying All-Pass Chained Rule Delegations
More Plaid interview questions
- Total Runtime of Queued Tasks Across Workers 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