Implement a web logger, which provide two methods:

  1. hit(timestamp) , record a hit at given timestamp.
  2. get_hit_count_in_last_5_minutes(timestamp) , get hit count in last 5 minutes.

the two methods will be called with non-descending timestamp (in sec).

Have you met this question in a real interview?

Yes

Example

hit(1);
hit(2);
get_hit_count_in_last_5_minutes(3);

>
>
 2
hit(300);
get_hit_count_in_last_5_minutes(300);

>
>
 3
get_hit_count_in_last_5_minutes(301);

>
>
 2

struct Node {
  int timestamp;
  int time;
  Node (int timestamp, int time) {
      this->timestamp = timestamp;
      this->time = time;
  }
};

class WebLogger {
private:
    int counter;
    deque<Node> q;
public:
    WebLogger() {
        // initialize your data structure here.
        counter = 0;
    }

    /**
     * @param timestamp an integer
     * @return void
     */
    void hit(int timestamp) {
        // Write your code here
        counter++;
        if (!q.empty() && q.back().timestamp == timestamp) {
            q.back().time++;
        } else {
            q.push_back(Node(timestamp, 1));
        }
    }

    /**
     * @param timestamp an integer
     * @return an integer
     */
    int get_hit_count_in_last_5_minutes(int timestamp) {
        // Write your code here
        while (!q.empty() && q.front().timestamp + 300 <= timestamp) {
            counter -= q.front().time;
            q.pop_front();
        }
        return counter;
    }
};

results matching ""

    No results matching ""