#3508

Implement Router

expert · 1040 · lc medium +32 · 39.1% accepted · 479 likes · top 18%

Description

Implement a Router class to manage network packets, each with a source, destination, and timestamp.

Router(int memoryLimit): Initializes with a max capacity of memoryLimit packets. When full, the oldest packet is evicted to make room.

bool addPacket(int source, int destination, int timestamp): Inserts the packet if it is not a duplicate (same source, destination, and timestamp). Returns true on success, false for duplicates.

int[] forwardPacket(): Removes and returns the oldest packet as [source, destination, timestamp], or an empty array if none remain.

int getCount(int destination, int startTime, int endTime): Returns the count of stored (not yet forwarded) packets matching the given destination with timestamp in [startTime, endTime].

AddPacket calls arrive in non-decreasing timestamp order.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20