This is an interview question I got recently. It is likely to related to some front-web development, which I do not have much experience with.
The question is "How do you calculate the number of visits a website receives in the last 5 minutes"?
/* Alright, according to the comments and downvotes, I decide to write more of my/my friend's thoughts. My current solution is to construct a queue storing time stamps of the visits. Given a new visit, I erase all visits 5 minutes earlier and then add this new visit. But this seems to be not efficient 1) removing elements in the front of a queue is not efficient, 2) the length of the queue is as long as # of visits. */
The interviewer asks for code and I have no idea about it.
Any suggestion/comments are appreciated!
Disclaimer: since it is of your interest to understand the problem and possible solutions, I am not adding any code, just some thoughts, and you can (and should) think about it and do your own code afterwards.
One detail might make a difference in the way you store data: What is the granularity of your "minute"? Is it only a minute, is it 60 seconds or is it 60,000 milliseconds? For example, let's assume your current timestamp is 03:44:30,820. Does a request received at 03:39:31,820 occur within "the last 5 minutes" or not? If your "minute" granularity is one minute, it does not (only requests on 03:44, 03:43, 03:42, 03:41 and 03:40 do). If your "minute" granularity is 60 seconds, it does occur within the last 5 minutes.
So, assuming your "minute" granularity is 1 minute (for the sake of simplicity). This way, your "queue" is only 5 positions long. Each position can contain the count of requests that occurred in that minute. Your problem #2 is over. Also, if you have a linked list instead of a queue, you can maintain a head
and a tail
pointer, also getting rid of your problem #1.
A possible optimization (that might complicate a little bit the code in case some minutes do not have any request, but anyway worth exploring) is: since your list has a fixed size (in this case, 5), you can also use a circular buffer, getting rid of your pair of pointers, keeping only a last
pointer.
These are just some ideas, but the intent of the interviewer was probably to make you think about the problem, ask some questions, throw some ideas out, and only then derive some code from it.