1163. Router Buffer Drops

Medium3.5 points estimatedQueueSimulation

A small router has one outgoing link and a buffer holding at most capacity packets, counting the packet currently being sent. Packet i arrives at time arrivals[i] (arrival times never decrease) and needs durations[i] time units on the link. Accepted packets are sent one at a time in arrival order, and a packet starts as soon as it has arrived and the link is free.

Before a packet arriving at time t is considered, every accepted packet whose transmission finishes at or before t leaves the buffer. If the buffer is still full, the new packet is dropped and never uses the link. Return an array with, for each packet, the time its transmission starts, or -1 if it was dropped. Here 1 <= n <= 1000, 0 <= arrivals[i] <= 10^6, 1 <= durations[i] <= 1000 and 1 <= capacity <= 1000.

Keep a queue of finish times for O(n) time and O(n) space.

Example 1

Input:
arrivals = [0,1,2,3]durations = [5,5,5,5]capacity = 2
Output:
[0,5,-1,-1]
Explanation:

Packet 0 runs from 0 to 5, packet 1 waits and starts at 5, and packets 2 and 3 find two packets in the buffer, so both are dropped.

Example 2

Input:
arrivals = [0,0,10], durations = [3,3,3], capacity = 1
Output:
[0,-1,10]
Explanation:

Packet 1 arrives while packet 0 occupies the single slot and is dropped; by time 10 the link is empty, so packet 2 starts at once.

Constraints

1 ≤ n ≤ 1000; arrivals.length == durations.length

0 ≤ arrivals[i] ≤ 106, non-decreasing

1 ≤ durations[i] ≤ 1000

1 ≤ capacity ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…