Hired.com Interview Question
Java DevelopersCountry: United States
Interview Type: Phone Interview
@emb Yes. This is what is given to me and you can add any member/methods on top of this class. When this deals with a size limited buffer, there should be an eviction logic along with this. For example, limitBuffer(1000, 20) means that the instance can hold a maximum of 20 items in 1 millisecond. If there are about 20 items and a new item is about to be added within a span of 1 millisecond, the class should call alert stating that this item could not be added because maximum capacity has exceeded. A few practical examples that I can think about is the maximum messages that can be held by a mailbox for a year or the maximum api calls that is held per day.
class LimitBuffer
{
long m_wms;
int m_threshold;
long m_startt;
long m_lastt;
int m_count;
class Event
{
String name;
long time;
Event(String name,long time) {
this.name = name;
this.time = time;
}
}
LinkedList<Event> eventlist;
public LimitBuffer(long windowMs, int threshold)
{
eventlist = new LinkedList<Event>();
m_startt = System.currentTimeMillis( );
m_count = 0;
m_wms = windowMs;
m_threshold = threshold;
}
private void alert(String eventName)
{
System.out.println(eventName);
}
public void addEvent(String eventName)
{
m_lastt=System.currentTimeMillis( );
Event a = new Event(eventName,m_lastt);
eventlist.add(a);
m_count++;
if(m_count >= m_threshold)
{
Event x = eventlist.removeFirst();
m_count—;
if(x.time - m_lastt< m_wms)
alert(x.name); }
}
}
Follow up. What if you wanted to improve on the storage space? e.g. I got a million items for a window and I wouldn't want to store all of them in memory.
- dmachop June 11, 2016