KatInterview

Finish Times for a Single Worker with a Limited Waiting Line

Stacks & QueuesAuto-graded · 20 test cases
MediumAuto-gradedStacks & Queuesqueuedequesimulation

Last updated

Simulate a one-worker FIFO queue with a capped waiting line and report each job's finish time or -1 if it was rejected, using a deque of finish times.

Job Processing with a Capped Waiting Line

A service has exactly one worker. Jobs show up over time, and the worker handles them one at a time. Once the worker begins a job, it runs until the job is done and cannot be interrupted.

You are given an integer waiting_capacity, the largest number of jobs that may be waiting at the same moment. The job the worker is currently running does not count toward this limit. You are also given a list jobs, where each entry is a pair [arrival, length]:

  • arrival: the time at which the job reaches the service.
  • length: how long the worker needs to run the job.

Rules

  1. The worker runs at most one job at a time, and a job that has started runs to completion.
  2. When a job arrives at time arrival:
    • Every job whose finish time is less than or equal to arrival has already left the system.
    • If the worker is idle, the new job starts right away.
    • If the worker is busy and the number of jobs currently waiting is strictly less than waiting_capacity, the new job joins the waiting line.
    • Otherwise (the worker is busy and the waiting line already holds waiting_capacity jobs), the new job is rejected immediately and never runs.
  3. Waiting jobs are served in first-come, first-served order. Jobs with the same arrival time are handled in the order they appear in jobs.

Task

Return a list of integers with one entry per job, in input order. Entry i is the time at which job i finishes running, or -1 if job i was rejected.

If jobs is empty, return an empty list.

Constraints

  • 0 <= waiting_capacity <= 10^5
  • 0 <= len(jobs) <= 10^5 (the list may be empty)
  • 0 <= arrival <= 10^9
  • 1 <= length <= 10^9
  • Jobs are given in non-decreasing order of arrival.

Examples

Example 1

Input: job_finish_times(1, [[1, 5], [2, 4], [3, 3], [7, 2]])

Output: [6, 10, -1, 12]

Example 2

Input: job_finish_times(0, [[0, 3], [2, 2], [3, 1]])

Output: [3, -1, 4]

Hints

Hint 1

You do not need to simulate every tick of a clock. Once a job is accepted, its finish time is fixed, because later arrivals cannot change the FCFS order.

Hint 2

Keep the finish times of all accepted jobs that are still in the system (the running one plus the waiting ones) in a deque. Before handling an arrival, pop from the front every finish time that is <= the arrival time.

Hint 3

After removing finished jobs, if the deque is empty the worker is idle. Otherwise the front job is running and the waiting count is len(deque) - 1. A new accepted job starts at the last finish time in the deque (or at its arrival if the deque is empty).