#include <bits/stdc++.h>
using namespace std;
class EventCounter
{
public:
int expiry;
deque<pair<string,long>> history;
unordered_map<string,int> keyCount;
EventCounter (int millis)
{
this->expiry = millis;
}
void cleanup(long timestamp)
{
while(history.size()>0)
{
auto node = history.front();
if(timestamp - node.second > expiry)
{
if(keyCount.count(node.first))
{
int cnt = keyCount[node.first];
keyCount[node.first] = cnt-1;
if(keyCount[node.first]==0)
{
keyCount.erase(node.first);
}
}
history.pop_front();
}
else
{
break;
}
}
}
void put(string element,long timestamp)
{
//cleanup(timestamp);
history.push_back({element,timestamp});
if(keyCount.count(element))
{
int existingcount = keyCount[element];
keyCount[element] = existingcount +1;
}
else
{
keyCount[element]= 1;
}
}
int getTotalCount(long timestamp)
{
cleanup(timestamp);
return history.size();
}
int getKeyCount(string element, long timestamp)
{
cleanup(timestamp);
if(keyCount.count(element))
{
return keyCount[element];
}
else
{
return 0;
}
}
};
int main() {
// your code goes here
EventCounter counter(300*1000); // 300 second window
// Simulation of events
counter.put("login", 1000);
counter.put("click", 2000);
counter.put("login", 3000);
cout << "Login count at 3s: " << counter.getKeyCount("login", 3000) << endl; // 2
cout << "Total events at 3s: " << counter.getTotalCount(3000) << endl; // 3
// Simulation of expiration: Jump to 301.5 seconds (301500 ms)
// The "login" at 1000ms expires.
cout << "Total events at 301.5s: " << counter.getTotalCount(301500) << endl; // 2
return 0;
return 0;
}