From ade46778cfada93d70f6e39ce0c91891697a1bce Mon Sep 17 00:00:00 2001 From: chayan das Date: Sat, 20 Sep 2025 10:44:52 +0530 Subject: [PATCH] Create 3508. Implement Router --- 3508. Implement Router | 71 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 3508. Implement Router diff --git a/3508. Implement Router b/3508. Implement Router new file mode 100644 index 0000000..d4b9734 --- /dev/null +++ b/3508. Implement Router @@ -0,0 +1,71 @@ +class Router { +public: + int limit = 0; + set> packets; + unordered_map removedPacketsFromDestination; + unordered_map> pD; + + queue> q; + Router(int memoryLimit) { limit = memoryLimit; } + + bool addPacket(int source, int destination, int timestamp) { + if (packets.find({source, destination, timestamp}) != packets.end()) { + return false; + } + if (q.size() > 0) { + + if (limit == q.size()) { + + vector p = q.front(); + + packets.erase(p); + removedPacketsFromDestination[p[1]]++; + + q.pop(); + } + } + + q.push({source, destination, timestamp}); + pD[destination].push_back(timestamp); + packets.insert({source, destination, timestamp}); + return true; + } + + vector forwardPacket() { + if (q.size() > 0) { + vector p = q.front(); + packets.erase(p); + removedPacketsFromDestination[p[1]]++; + q.pop(); + return p; + } + + return {}; + } + + int getCount(int destination, int startTime, int endTime) { + + if (pD.find(destination) == pD.end()) { + return 0; + } + + int x = removedPacketsFromDestination[destination]; + + auto it = lower_bound(pD[destination].begin() + x, + pD[destination].end(), startTime); + + auto it2 = upper_bound(pD[destination].begin() + x, + pD[destination].end(), endTime); + + int count = int(it2 - it); + return count; + } +}; + +/** + * Your Router object will be instantiated and called as such: + * Router* obj = new Router(memoryLimit); + * bool param_1 = obj->addPacket(source,destination,timestamp); + * vector param_2 = obj->forwardPacket(); + * int param_3 = obj->getCount(destination,startTime,endTime); + */