Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions 3508. Implement Router
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
class Router {
public:
int limit = 0;
set<vector<int>> packets;
unordered_map<int, int> removedPacketsFromDestination;
unordered_map<int, vector<int>> pD;

queue<vector<int>> 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<int> 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<int> forwardPacket() {
if (q.size() > 0) {
vector<int> 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<int> param_2 = obj->forwardPacket();
* int param_3 = obj->getCount(destination,startTime,endTime);
*/
Loading