Design Hit Counter in C++


Suppose we want to design a hit counter which counts the number of hits received in the past 5 minutes. There will be a function and that accepts a timestamp parameter in the second unit and we may assume that calls are being made to the system in chronological order (so, the timestamp is monotonically increasing). We also assume that the earliest timestamp starts at 1.

It is possible that several hits arrive roughly at the same time.

So we will call the hit() function to hit and getHits() function to get the count of hits.

To solve this, we will follow these steps −

  • Define an array time of size 300

  • Define an array hits of size 300

  • Define a function hit(), this will take timestamp,

  • idx := timestamp mod 300

  • if time[idx] is not equal to timestamp, then −

    • time[idx] := timestamp

    • hits[idx] := 1

  • Otherwise

    • hits[idx] := hits[idx] + 1

  • Define a function getHits(), this will take timestamp,

  • ret := 0

  • for initialize i := 0, when i < 300, update (increase i by 1), do −

    • if timestamp - time[i] < 300, then −

      • ret := ret + hits[i]

  • return ret

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class HitCounter {
public:
   vector<int< time;
   vector<int< hits;
   HitCounter(){
      time = vector<int<(300);
      hits = vector<int<(300);
   }
   void hit(int timestamp){
      int idx = timestamp % 300;
      if (time[idx] != timestamp) {
         time[idx] = timestamp;
         hits[idx] = 1;
      }
      else {
         hits[idx] += 1;
      }
   }
   int getHits(int timestamp){
      int ret = 0;
      for (int i = 0; i < 300; i++) {
         if (timestamp - time[i] < 300) {
            ret += hits[i];
         }
      }
      return ret;
   }
};
main(){
   HitCounter ob;
   ob.hit(1);
   ob.hit(2);
   ob.hit(3);
   cout << (ob.getHits(4)) << endl;
   ob.hit(300);
   cout << (ob.getHits(300)) << endl;
   cout << (ob.getHits(301));
}

Input

ob.hit(1);
ob.hit(2);
ob.hit(3);
ob.getHits(4);
ob.hit(300);
ob.getHits(300);
ob.getHits(301);

Output

3
4
3

Updated on: 19-Nov-2020

351 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements