logo CodeStepByStep logo

HitCounter

Language/Type: Java classes algorithms interview
Related Links:

Write a class of objects named HitCounter that keeps track of "hits" or visits to a web site. The idea is that we want to count hits on the site and be able to return the total number of hits in a given time window.

Your class must have the following public members:

member name description
HitCounter(window) Constructs a new hit counter for the given window of time. For example, if the window is 10, the hit counter keeps track of hits within the last 10 time increments. The initial time when the counter is constructed is 0. You may assume the window is ≥ 0.
hit(time) Records that a user visited the site at the given time. Also updates the notion of the "current time" to the given time. You may assume that the time passed is greater than or equal to the previously current time.
getHits(time) Returns the total number of hits that have occured within the given window at the given current time. If the given time is outside the current window range, return 0.

For example:

HitCounter counter = new HitCounter(5);
counter.hit(1);
counter.hit(3);
int hits4 = counter.getHits(4);     // 2

counter.hit(6);
counter.hit(6);                     // multiple hits for the same time
counter.hit(7);
int hits7 = counter.getHits(7);     // 4  (hit from time 1 is now out of window)
int hits10 = counter.getHits(10);   // 3  (hit from time 3 is now out of window)
int hits15 = counter.getHits(15);   // 0  (all hits are now out of window)

Part of the challenge of this problem lies in coming up with an efficient implementation.

You should define the entire class including the class heading, the private fields, and the declarations and definitions of all the public methods and constructor.

Class: Write a complete Java class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.