Problem Description
Design a Router data structure that stores data packets with attributes source, destination, and timestamp. The router has a fixed memory limit; if adding a new packet exceeds this limit, the oldest packet is removed. Duplicate packets (with the same source, destination, and timestamp) should not be added. In addition, the router supports forwarding (removing the oldest packet in FIFO order) and counting how many packets with a given destination have timestamps in a specified inclusive range.
Key Insights
- Use a FIFO queue to store packets in the order they arrive.
- Maintain a set of packet identifiers (source, destination, timestamp) for quick duplicate detection.
- Use an auxiliary mapping from destination to a sorted list of timestamps to support range queries efficiently.
- When the memory limit is reached, remove the oldest packet from both the queue and the auxiliary data structures.
- Since packets are added in increasing order of timestamp, the timestamp lists for each destination will naturally be sorted.
Space and Time Complexity
Time Complexity:
- addPacket: O(1) for addition + O(log n) for insertion in the destination list (if using binary search for insertion, but here we append since timestamps are non-decreasing) = O(1)
- forwardPacket: O(1) for queue removal, O(1) for removal from auxiliary structure if done from the beginning.
- getCount: O(log m) per query on the list for the given destination where m is the number of packets with that destination. Space Complexity:
- O(memoryLimit) for storing the packets in the queue, set, and auxiliary mapping.
Solution
We maintain three main data structures:
- A FIFO queue (e.g. deque) to store the packets.
- A set that holds tuples (source, destination, timestamp) to quickly check for duplicates.
- A dictionary (or hashmap) mapping each destination to a list of timestamps. Since packets are added in non-decreasing order of timestamp, we can simply append new timestamps. For delete operations (which always remove the oldest packet), we remove from the beginning of the list. When adding a new packet, if the memory limit is reached, we remove the oldest packet from all three data structures. The getCount function uses binary search over the list of timestamps for the specified destination to count packets within the given time range.