Skip to content

Practice Implement Router

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#3508
LeetCode Problem

Implement Router

Problem Statement

Implement Router(memoryLimit), which stores at most memoryLimit packets in arrival order. Each packet has [source, destination, timestamp]. addPacket(source, destination, timestamp) rejects a triple already stored and returns false; otherwise it evicts the oldest packet if full, appends the new packet, and returns true. forwardPacket() removes and returns the oldest packet as that triple, or returns an empty array when none exists. getCount(destination, startTime, endTime) counts currently stored packets for that destination with timestamps in the inclusive interval. Calls to addPacket have non-decreasing timestamps.

Source: Implement Router on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["Router", "addPacket", "addPacket", "addPacket", "addPacket", "addPacket", "forwardPacket", "addPacket", "getCount"] [[3], [1, 4, 90], [2, 5, 90], [1, 4, 90], [3, 5, 95], [4, 5, 105], [], [5, 2, 110], [5, 100, 110]]
Output
[null, true, true, false, true, true, [2, 5, 90], true, 1]

# Example 2

Input
["Router", "addPacket", "forwardPacket", "forwardPacket"] [[2], [7, 4, 90], [], []]
Output
[null, true, [7, 4, 90], []]

Constraints

2 <= memoryLimit <= 10^5
1 <= source, destination <= 2 * 10^5
1 <= timestamp <= 10^9
1 <= startTime <= endTime <= 10^9
At most 10^5 calls will be made to addPacket, forwardPacket, and getCount methods altogether.
queries for addPacket will be made in non-decreasing order of timestamp.

Related LeetCode Problems

Practice more problems similar to Implement Router.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.