Design a multi-timer using single underlying timer
GoogleSoftware Engineer · Online AssessmentLast updated
This question evaluates a candidate's ability to implement timer scheduling, resource multiplexing, and concurrency control using constrained system primitives, testing understanding of timers, event handling, data structures, and correctness under race conditions.
You are given a Timer class that has access to a single underlying system timer API that can only keep one active timer at a time.
Underlying single-timer primitives (already available)
class Timer {
// Schedule ONE timer to fire at `timestamp` (absolute time).
// If called again, it overrides/cancels the previously scheduled system timer.
private void setTimer(long timestamp);
// Called automatically when the currently scheduled system timer expires.
private void handleTimer();
// Returns current time as an absolute timestamp (same unit as setTimer).
private long getCurrentTime();
// Public API: users can call this to schedule MANY timers.
public void setNewTimer(long timestamp);
}
Requirements
- Users can only call
setNewTimer(timestamp). setNewTimermust support multiple outstanding timers.- When any user timer expires,
handleTimer()should be invoked (once per expired user timer). - You must implement the logic of the four methods so that multiple user timers are correctly managed on top of the single underlying
setTimer.
Clarifications you may assume
timestampis an absolute time value (e.g., epoch milliseconds) comparable togetCurrentTime().- Multiple user timers may share the same timestamp.
- If a timer is set for a time ≤
getCurrentTime(), it should fire “immediately” (as soon as the system can schedule it).
Discuss data structures, time/space complexity, and important edge cases (e.g., overrides, duplicate timestamps, and concurrency if relevant).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.