KatInterview

Calculate Processed Work Units in Pipelined Task Queues

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programmingarrayssimulationdynamic-programming

Last updated

Simulate task batch execution across a sequential multi-stage pipeline and count total units completed within a time limit.

You are configuring an asynchronous pipeline consisting of $K$ sequential processing nodes numbered $0$ to $K - 1$.

Each node $i$ is specified as a tuple (capacity, step_time):

  • capacity: The maximum number of task units the node can process simultaneously ($capacity \ge 1$).
  • step_time: The time taken to execute one full execution cycle at this node ($step_time \ge 0$).

A sequence of task groups is pushed into the pipeline starting at time $t = 0$. You are given an array batches, where batches[j] denotes the number of units in group $j$.

The system operates under the following constraints:

  1. Parallel Execution Cycles: At node $i$, a group containing $B$ units is processed in consecutive cycles. Each cycle runs up to capacity units and takes step_time units of time. The total cycles needed for group $j$ at node $i$ is $\lceil B / capacity \rceil$. If $B = 0$, processing takes $0$ time.
  2. Barrier Synchronization: Group $j$ cannot begin processing at node $i + 1$ until all units in group $j$ have completely finished processing at node $i$.
  3. Sequential Node Availability: A node can handle only one task group at a time. Node $i$ cannot start group $j$ until it finishes group $j - 1$.
  4. Pipeline Concurrency: Different nodes can process different task groups concurrently.
  5. Deadline Condition: A task group counts toward the total completed units if and only if its execution through the final node ($K - 1$) finishes at or before deadline. If a group exceeds the deadline, none of its units are counted.

Calculate and return the total number of task units that successfully finish execution by the given deadline.

Constraints

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

Examples

Example 1

Input: count_completed_jobs([[2, 3], [1, 4]], [3, 2], 20)

Output: 3

Example 2

Input: count_completed_jobs([[3, 2]], [0, 5], 4)

Output: 5

Hints

Hint 1

For each batch $j$ and node $i$, determine the start time by considering two availability bounds: when node $i$ finishes batch $j - 1$, and when batch $j$ finishes node $i - 1$.

Hint 2

The total execution time for a batch $B$ with capacity $C$ and duration $D$ is $\lceil B / C \rceil \times D$. Use integer division `(B + C - 1) // C` to avoid precision issues.

Hint 3

Track state using an array of length $K$ for when each node becomes free, alongside a scalar variable for when the current batch clears its previous stage.