Simulate Multi-Timer Expiry with Single System Timer
Heaps, Sorting & SearchAuto-graded · 18 test casesLast updated
Simulate the execution and triggering order of multiple scheduled timers using a min-heap under system clock advancements.
Design an event-driven timer scheduler that multiplexes multiple user-requested timer deadlines onto a single underlying hardware/system timer.
You are given a sequence of operations representing user requests and time advances:
"setNewTimer"with parameter[t]: Schedules a new user timer to fire at absolute timestampt."advanceTo"with parameter[T]: Advances the current system clock to absolute timestampT. When the clock advances, any scheduled timer with a timestamp less than or equal toTexpires and fires immediately in chronological order.
Write a function that processes a stream of these operations and returns a list containing the timestamps of all user timers that fired, in the exact chronological order of their expiration.
If multiple timers share the same timestamp, they should all fire when the clock reaches or passes that timestamp, maintain their presence, and appear consecutively in the output.
Constraints
1 <= len(operations) == len(arguments) <= 10^5operations[i]is either"setNewTimer"or"advanceTo".- For
"setNewTimer",arguments[i]is a list containing a single integertwhere0 <= t <= 10^9. - For
"advanceTo",arguments[i]is a list containing a single integerTwhere0 <= T <= 10^9. - The values of
Tin"advanceTo"operations are non-decreasing.
Examples
Example 1
Input: multi_timer_firings(['setNewTimer', 'setNewTimer', 'advanceTo', 'advanceTo'], [[5], [3], [3], [5]])
Output: [3, 5]
Example 2
Input: multi_timer_firings(['setNewTimer', 'setNewTimer', 'advanceTo'], [[4], [4], [4]])
Output: [4, 4]
Hints
Hint 1
Since the underlying hardware timer can only set one target time, it should always be armed with the earliest active user deadline.
Hint 2
Which data structure allows efficient insertion of new deadlines and quick retrieval of the minimum deadline?
Hint 3
When advancing the clock, repeatedly extract all deadlines from the priority queue that are less than or equal to the current time.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To multiplex multiple pending timer events using a single hardware timer:
- The underlying hardware timer must always be set to wake up at the earliest pending user deadline.
- We can maintain all pending target timestamps in a priority queue (min-heap).
- When
"setNewTimer"is invoked with deadlinet, we pushtonto the min-heap. - When
"advanceTo"is invoked with clock valueT, we update our reference time toTand continuously pop from the min-heap while the smallest timestamp in the heap is<= T. Each popped element is recorded in our list of fired timers.
Complexity
- Time Complexity:
- Inserting a timer takes $O(\log N)$ time where $N$ is the number of active timers.
- Advancing time pops $k$ expired timers, taking $O(k \log N)$ total time.
- Overall time complexity for $M$ operations is $O(M \log N)$.
- Space Complexity: $O(N)$ auxiliary space to store pending timers in the min-heap.
Python Reference Solution
import heapq
from typing import List
def multi_timer_firings(operations: List[str], arguments: List[List[int]]) -> List[int]:
timers = []
fired = []
current_time = 0
for operation, args in zip(operations, arguments):
if operation == "setNewTimer":
heapq.heappush(timers, args[0])
elif operation == "advanceTo":
current_time = args[0]
while timers and timers[0] <= current_time:
fired.append(heapq.heappop(timers))
else:
raise ValueError("unknown operation")
return fired