fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. class EventCounter
  5. {
  6. public:
  7. int expiry;
  8. deque<pair<string,long>> history;
  9. unordered_map<string,int> keyCount;
  10. EventCounter (int millis)
  11. {
  12. this->expiry = millis;
  13. }
  14.  
  15. void cleanup(long timestamp)
  16. {
  17. while(history.size()>0)
  18. {
  19. auto node = history.front();
  20. if(timestamp - node.second > expiry)
  21. {
  22. if(keyCount.count(node.first))
  23. {
  24. int cnt = keyCount[node.first];
  25. keyCount[node.first] = cnt-1;
  26. if(keyCount[node.first]==0)
  27. {
  28. keyCount.erase(node.first);
  29. }
  30. }
  31. history.pop_front();
  32. }
  33. else
  34. {
  35. break;
  36. }
  37. }
  38. }
  39.  
  40. void put(string element,long timestamp)
  41. {
  42. //cleanup(timestamp);
  43. history.push_back({element,timestamp});
  44. if(keyCount.count(element))
  45. {
  46. int existingcount = keyCount[element];
  47. keyCount[element] = existingcount +1;
  48. }
  49. else
  50. {
  51. keyCount[element]= 1;
  52. }
  53.  
  54. }
  55.  
  56. int getTotalCount(long timestamp)
  57. {
  58. cleanup(timestamp);
  59. return history.size();
  60. }
  61.  
  62. int getKeyCount(string element, long timestamp)
  63. {
  64. cleanup(timestamp);
  65. if(keyCount.count(element))
  66. {
  67. return keyCount[element];
  68. }
  69. else
  70. {
  71. return 0;
  72. }
  73. }
  74.  
  75. };
  76.  
  77. int main() {
  78. // your code goes here
  79. EventCounter counter(300*1000); // 300 second window
  80.  
  81. // Simulation of events
  82. counter.put("login", 1000);
  83. counter.put("click", 2000);
  84. counter.put("login", 3000);
  85.  
  86. cout << "Login count at 3s: " << counter.getKeyCount("login", 3000) << endl; // 2
  87. cout << "Total events at 3s: " << counter.getTotalCount(3000) << endl; // 3
  88.  
  89. // Simulation of expiration: Jump to 301.5 seconds (301500 ms)
  90. // The "login" at 1000ms expires.
  91. cout << "Total events at 301.5s: " << counter.getTotalCount(301500) << endl; // 2
  92.  
  93. return 0;
  94. return 0;
  95. }
Success #stdin #stdout 0s 5324KB
stdin
Standard input is empty
stdout
Login count at 3s: 2
Total events at 3s: 3
Total events at 301.5s: 2