Google Interview Question
Software EngineersCountry: United States
Something is missing in the question. As there are many corner cases which will can not be satisfied with given conditions for e.g. At time 0 request to call setTimer(10, callback) and a second later another request comes in to setTimer(3, callback) . since 10 second timer is already running and its not allowed to be changed..there is no way to satisfy second request. At the time of firing the 10 second time there was no a priori knowledge of what is to come.
Assuming user requests are not known and come at random, the requests can be scheduled according to their callback time.
i. e. if the user creates timer at t as timer.startTimer(x, callback), then (t+x) is the callback time when the user will get callback.
So we maintain a min heap using callback time as the priority criteria and select request with most recent callback time to be scheduled with the system timer. We keep adding to the heap when new request for creating timer arrives.
But there are certain edge cases. For example, if a user creates a timer at time t as timer.startTimer(3,callback) and at (t+1) creates another timer as timer.startTimer(1,callback), then the second request should be scheduled to the system timer before the first request (t+1+1 < t+3) because otherwise it cannot be scheduled. If the first request is assigned to the system timer as soon as it arrives, the second request cannot be satisfied. So, we remove remove from priority queue only when the callback time is 1 second later.
Time complexity for n requests: O(nlogn)
- noname May 03, 2019