KatInterview

Simulate Multi-Timer Expiry with Single System Timer

Heaps, Sorting & SearchAuto-graded · 18 test cases
MediumAuto-gradedHeaps, Sorting & Searchheappriority-queuedesign

Last 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 timestamp t.
  • "advanceTo" with parameter [T]: Advances the current system clock to absolute timestamp T. When the clock advances, any scheduled timer with a timestamp less than or equal to T expires 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^5
  • operations[i] is either "setNewTimer" or "advanceTo".
  • For "setNewTimer", arguments[i] is a list containing a single integer t where 0 <= t <= 10^9.
  • For "advanceTo", arguments[i] is a list containing a single integer T where 0 <= T <= 10^9.
  • The values of T in "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.