Monitor Concurrent Simulations for Idle Timeouts

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement a stateful SimulationMonitor class that tracks thousands of concurrent simulation runs from an incoming stream of timestamped activity records and reports runs that go silent past a fixed idle threshold.

class SimulationMonitor:
    def __init__(self, timeout: int): ...
    def process_event(self, sim_id: Hashable, event_type: str, timestamp: int) -> List[Hashable]: ...
    def is_active(self, sim_id: Hashable) -> bool: ...
    def active_count(self) -> int: ...

Constructor & Query Methods

  • SimulationMonitor(timeout): Configure the idle threshold timeout (timeout >= 0, measured in the same integer time units as event timestamps). Raise ValueError if timeout < 0.
  • is_active(sim_id): Return True if sim_id currently has an open run that has neither finished normally nor expired, and False otherwise.
  • active_count(): Return how many simulations are currently active.

Event Processing Rules (process_event)

Valid calls arrive in monotonically non-decreasing timestamp order (timestamp >= previous_timestamp), with event_type equal to "start", "ping", or "end":

  1. Validate before mutating: If event_type is unrecognized or timestamp is strictly less than the most recently accepted event's timestamp, raise ValueError immediately while leaving all internal monitor state untouched.
  2. Apply the incoming event at timestamp:
    • "start": Marks sim_id active with its latest activity time set to timestamp. If sim_id had previously finished or timed out, this opens a brand-new run; if sim_id is already active, this refreshes its latest activity time to timestamp.
    • "ping": Updates sim_id's latest activity time to timestamp if sim_id is currently active; ignored if sim_id is not active.
    • "end": Closes sim_id normally so it is no longer active; ignored if sim_id is not active.
  3. Collect newly expired runs: After applying the event, every currently active simulation satisfying the strict inequality timestamp - last_activity > timeout expires:
    • Remove each expired simulation from the active set so that run is never reported a second time (and any later "ping" or "end" for that finished run is ignored unless a fresh "start" arrives).
    • Return the newly expired sim_id values ordered from oldest last_activity to newest, breaking ties by the order in which those last_activity updates were recorded.

Examples

Example 1

monitor = SimulationMonitor(timeout=5)
monitor.process_event("sim_x", "start", 10)  # -> []
monitor.process_event("sim_y", "start", 12)  # -> []
monitor.process_event("sim_x", "ping", 14)   # -> []
monitor.process_event("sim_z", "start", 19)  # -> ["sim_y"]
monitor.process_event("sim_z", "ping", 20)   # -> ["sim_x"]
monitor.process_event("sim_x", "ping", 21)   # -> []  (ignored; sim_x is inactive)
monitor.process_event("sim_z", "end", 22)    # -> []  (active_count() == 0)

Walk-through: - "sim_x" starts at 10, "sim_y" starts at 12, and "sim_x" refreshes its activity to 14. - At t = 19, "sim_y" has been silent for 19 - 12 = 7 > 5 and is returned, whereas "sim_x" has been silent for 19 - 14 = 5 <= 5 and remains active because expiration requires strict >. - At t = 20, "sim_x" reaches idle duration 20 - 14 = 6 > 5 and expires. Its late "ping" at 21 is ignored, and "sim_z" closes cleanly at 22.

Example 2

monitor = SimulationMonitor(timeout=4)
monitor.process_event("run_b", "start", 2)   # -> []
monitor.process_event("run_a", "start", 2)   # -> []
monitor.process_event("run_c", "start", 3)   # -> []
monitor.process_event("run_d", "start", 8)   # -> ["run_b", "run_a", "run_c"]
monitor.process_event("run_b", "start", 9)   # -> []  (active_count() == 2)

Walk-through: At t = 8, "run_b", "run_a", and "run_c" all exceed timeout = 4 (6 > 4 and 5 > 4). "run_b" and "run_a" share last_activity = 2 and are emitted in arrival order ("run_b" first), followed by "run_c". Calling "start" on "run_b" at t = 9 launches a new active run alongside "run_d".

Constraints

  • timeout >= 0 (ValueError on negative values).
  • sim_id can be any hashable value (strings and integers may appear together in the same monitor, so sim_id values may not be mutually comparable with <).
  • Accepted timestamp integers are monotonically non-decreasing across calls.
  • Because the monitor runs continuously over large streams, aim for O(1) amortized (or O(log n)) time per event and O(n) memory proportional only to the number of currently active runs n.

Step-by-step walkthrough

  1. Clarify the rules and event-processing order

    We are building a stateful SimulationMonitor(timeout) that ingests activity tuples (sim_id, event_type, timestamp) one by one in non-decreasing timestamp order:

    monitor = SimulationMonitor(timeout=5)
    monitor.process_event(sim_id, event_type, timestamp) -> list of newly expired sim_ids
    

    Before writing code, let's lock down every boundary detail:

    • Apply the incoming event first, then sweep for expirations: An active simulation sending a "ping" after a quiet stretch updates its own last_activity to timestamp before the expiration sweep runs (so it stays alive), and a "end" closes that run cleanly rather than flagging it as expired. (If a variant asked to expire before applying the incoming event, you would simply call _expire(timestamp) ahead of _apply(...).)
    • Strict inequality (>): A run expires only when timestamp - last_activity > timeout. With timeout = 5 and last_activity = 14, an event at 19 (19 - 14 = 5) leaves the run active; an event at 20 (20 - 14 = 6) expires it.
    • Single-report guarantee: Once expired, the run leaves the active set so subsequent events never report that run again.
    • Ignore "ping" or "end" on inactive IDs: Late heartbeats or duplicate "end" calls for runs that never started, already closed, or already expired must not revive them.
    • Restarting via "start": Sending "start" for an inactive sim_id launches a fresh run; sending "start" for an already-active sim_id refreshes its last_activity just like a "ping".
    • Deterministic tie-breaking & validation: Return expired IDs from oldest last_activity to newest (ties broken by activity arrival order), and raise ValueError before mutating state if event_type is unrecognized or timestamp decreases.
  2. Why scanning every active simulation is too slow

    A naive monitor keeps a plain dictionary last_activity[sim_id] = timestamp and loops across every active run after each call to test timestamp - last > timeout.

    That makes a simple reference oracle for tests, but each call costs O(n) time across n concurrent runs. With 100,000 active runs and 1,000,000 events, full scans perform up to 100,000,000,000 checks — almost all wasted re-inspecting runs that just reported activity. Only runs with the oldest last_activity can cross timeout first!

  3. First good design: hash map plus a min-heap (O(log H))

    A classic priority-queue approach pairs two structures:

    • Hash map latest[sim_id] storing the sequence number of each active run's newest activity (O(1) lookup).
    • Min-heap — a binary tree in an array keeping the smallest (last_activity, seq, sim_id) tuple at index 0 in O(log H) time per push or pop.

    Because moving an arbitrary node inside a binary heap is awkward, each "ping" pushes a fresh tuple onto the heap and leaves old tuples behind (lazy deletion — discarding outdated entries later when they surface at index 0).

    That achieves O(log H), though one noisy simulation pinging every millisecond inside a 5-second window can pile 5,000 stale entries into the heap (H >> n). Can we use monotonic timestamps to get O(1) updates and zero stale entries?

  4. Key insight: monotonic timestamps turn the heap into an O(1) queue

    Notice what every "start" or active "ping" sets last_activity to: the current event's timestamp. Because accepted timestamps never decrease (ts_1 <= ts_2 <= ts_3 <= ...), whichever simulation is touched right now always receives a last_activity greater than or equal to every other active simulation!

    That means "ordered from oldest last_activity to newest" is identical to "ordered from least-recently touched to most-recently touched"! Instead of a heap, we only need an ordered dictionary supporting three O(1) operations:

    Front (oldest activity)                                      Back (newest activity)
           |                                                               |
           v                                                               v
      [ "sim_y": 12 ] <------> [ "sim_x": 14 ] <------> [ "sim_z": 19 ]
           ^                            ^
      _expire() peeks and          hash table jumps directly to
      pops ONLY at the front!      any sim_id to delete or move_to_end!
    
    1. "start" or active "ping": set sim_id's timestamp and move its node to the back in O(1).
    2. "end": unlink sim_id from wherever it sits in O(1).
    3. Expiration sweep: peek at the front; while now - oldest_time > timeout, pop the front in O(1); the instant now - oldest_time <= timeout, stop immediately because every entry behind it is at least as recent!

    Python's collections.OrderedDict wires a hash table to a doubly linked list in C (the exact structure behind an LRU cache), giving us all three operations out of the box.

  5. Implement state, validation, and event updates

    Our state consists of self.timeout, self.current_time, and one OrderedDict named self.last_activity. Pay attention to two engineering details:

    1. Bounded O(n) memory for long-running processes: Whenever a run finishes or expires, we remove its key from self.last_activity. Because _apply ignores "ping" and "end" whenever sim_id not in self.last_activity, we never accumulate a historical graveyard of finished IDs!
    2. Explicit move_to_end(sim_id): Overwriting an existing key in OrderedDict (self.last_activity[sim_id] = timestamp) leaves that key at its old linked-list position! Calling self.last_activity.move_to_end(sim_id) immediately afterward moves the refreshed run to the back.
    from typing import Hashable, List
    from collections import OrderedDict
    
    
    class SimulationMonitor:
        """Tracks concurrent simulations and reports runs whose idle time exceeds timeout."""
    
        VALID_TYPES = ("start", "ping", "end")
    
        def __init__(self, timeout: int):
            if timeout < 0:
                raise ValueError("timeout must be >= 0")
            self.timeout = timeout
            # Timestamp of the most recently accepted event (None before the first event).
            self.current_time = None
            # self.last_activity: OrderedDict mapping active sim_id -> last_activity_timestamp,
            # ordered from oldest activity at the front to newest activity at the back,
            # e.g. OrderedDict([("B", 1), ("A", 2)]).
            self.last_activity = OrderedDict()
    
        def process_event(self, sim_id: Hashable, event_type: str, timestamp: int) -> List[Hashable]:
            # Phase 1: validate input BEFORE mutating state so rejected calls change nothing.
            if event_type not in self.VALID_TYPES:
                raise ValueError("unknown event type: " + repr(event_type))
            if self.current_time is not None and timestamp < self.current_time:
                raise ValueError("timestamps must not decrease")
    
            # Phase 2: advance the monitor clock and apply the incoming event.
            self.current_time = timestamp
            self._apply(sim_id, event_type, timestamp)
    
            # Phase 3: pop and report every active simulation that is now strictly past timeout.
            return self._expire(timestamp)
    
        def _apply(self, sim_id: Hashable, event_type: str, timestamp: int) -> None:
            if event_type == "end":
                # Normal completion: remove if active; ignore if unknown or already finished.
                self.last_activity.pop(sim_id, None)
                return
    
            if event_type == "ping" and sim_id not in self.last_activity:
                # Ignore pings for runs that never started, already ended, or already timed out.
                return
    
            # Either a "start" (new or active run) or a "ping" on an active run.
            # Because timestamps never decrease, `timestamp` is >= every value in the dict,
            # so moving `sim_id` to the back preserves sorted oldest-to-newest order.
            self.last_activity[sim_id] = timestamp
            self.last_activity.move_to_end(sim_id)
    
  6. Implement the front-to-back timeout sweep

    Inside _expire(self, now), next(iter(self.last_activity.items())) inspects the front (oldest_sim_id, oldest_time) pair in O(1) time:

    • If now - oldest_time <= self.timeout, the oldest active run is still within the threshold — and every run behind it has last_activity >= oldest_time, so we break right away.
    • Otherwise now - oldest_time > self.timeout, so self.last_activity.popitem(last=False) removes the front run in O(1) and appends oldest_sim_id to timed_out.
        def _expire(self, now: int) -> List[Hashable]:
            timed_out: List[Hashable] = []
            while self.last_activity:
                # Peek at the front entry, which always has the oldest last_activity timestamp.
                oldest_sim_id, oldest_time = next(iter(self.last_activity.items()))
                # Timeout requires strict `>` (idle for exactly `timeout` is still alive).
                if now - oldest_time <= self.timeout:
                    # Every entry behind the front was touched at `>= oldest_time`, so stop here.
                    break
                self.last_activity.popitem(last=False)
                timed_out.append(oldest_sim_id)
            return timed_out
    
        def is_active(self, sim_id: Hashable) -> bool:
            return sim_id in self.last_activity
    
        def active_count(self) -> int:
            return len(self.last_activity)
    

    Each started run enters self.last_activity once and is popped at most once, so across m events the total work inside _expire is bounded by O(m) — O(1) amortized per event!

  7. Walk through Example 1 step by step

    Let's trace timeout = 5 across all 7 calls in Example 1, showing self.last_activity from front (oldest) to back (newest):

    Event               After _apply                   Front checks in _expire                 Returned    Queue after
    ----------------------------------------------------------------------------------------------------------------------
    sim_x start 10      [sim_x:10]                     10 - 10 = 0 <= 5 -> stop                []          [sim_x:10]
    sim_y start 12      [sim_x:10, sim_y:12]           12 - 10 = 2 <= 5 -> stop                []          [sim_x:10, sim_y:12]
    sim_x ping  14      [sim_y:12, sim_x:14] (moved!)  14 - 12 = 2 <= 5 -> stop                []          [sim_y:12, sim_x:14]
    sim_z start 19      [sim_y:12, sim_x:14, sim_z:19] 19 - 12 = 7 > 5 -> pop sim_y;           ['sim_y']   [sim_x:14, sim_z:19]
                                                       19 - 14 = 5 <= 5 -> stop (strict >!)
    sim_z ping  20      [sim_x:14, sim_z:20]           20 - 14 = 6 > 5 -> pop sim_x;           ['sim_x']   [sim_z:20]
                                                       20 - 20 = 0 <= 5 -> stop
    sim_x ping  21      [sim_z:20] (inactive, ignored) 21 - 20 = 1 <= 5 -> stop                []          [sim_z:20]
    sim_z end   22      []                             queue empty                             []          []
    

    At t = 19, sim_x has been silent for 19 - 14 = 5 == timeout, so strict > keeps sim_x active until t = 20, and at t = 21 its late "ping" is ignored cleanly.

  8. Complete solution

    from typing import Hashable, List
    from collections import OrderedDict
    
    
    class SimulationMonitor:
        """Tracks concurrent simulations and reports runs whose idle time exceeds timeout."""
    
        VALID_TYPES = ("start", "ping", "end")
    
        def __init__(self, timeout: int):
            if timeout < 0:
                raise ValueError("timeout must be >= 0")
            self.timeout = timeout
            # Timestamp of the most recently accepted event (None before the first event).
            self.current_time = None
            # self.last_activity: OrderedDict mapping active sim_id -> last_activity_timestamp,
            # ordered from oldest activity at the front to newest activity at the back,
            # e.g. OrderedDict([("B", 1), ("A", 2)]).
            self.last_activity = OrderedDict()
    
        def process_event(self, sim_id: Hashable, event_type: str, timestamp: int) -> List[Hashable]:
            # Phase 1: validate input BEFORE mutating state so rejected calls change nothing.
            if event_type not in self.VALID_TYPES:
                raise ValueError("unknown event type: " + repr(event_type))
            if self.current_time is not None and timestamp < self.current_time:
                raise ValueError("timestamps must not decrease")
    
            # Phase 2: advance the monitor clock and apply the incoming event.
            self.current_time = timestamp
            self._apply(sim_id, event_type, timestamp)
    
            # Phase 3: pop and report every active simulation that is now strictly past timeout.
            return self._expire(timestamp)
    
        def _apply(self, sim_id: Hashable, event_type: str, timestamp: int) -> None:
            if event_type == "end":
                # Normal completion: remove if active; ignore if unknown or already finished.
                self.last_activity.pop(sim_id, None)
                return
    
            if event_type == "ping" and sim_id not in self.last_activity:
                # Ignore pings for runs that never started, already ended, or already timed out.
                return
    
            # Either a "start" (new or active run) or a "ping" on an active run.
            # Because timestamps never decrease, `timestamp` is >= every value in the dict,
            # so moving `sim_id` to the back preserves sorted oldest-to-newest order.
            self.last_activity[sim_id] = timestamp
            self.last_activity.move_to_end(sim_id)
    
        def _expire(self, now: int) -> List[Hashable]:
            timed_out: List[Hashable] = []
            while self.last_activity:
                # Peek at the front entry, which always has the oldest last_activity timestamp.
                oldest_sim_id, oldest_time = next(iter(self.last_activity.items()))
                # Timeout requires strict `>` (idle for exactly `timeout` is still alive).
                if now - oldest_time <= self.timeout:
                    # Every entry behind the front was touched at `>= oldest_time`, so stop here.
                    break
                self.last_activity.popitem(last=False)
                timed_out.append(oldest_sim_id)
            return timed_out
    
        def is_active(self, sim_id: Hashable) -> bool:
            return sim_id in self.last_activity
    
        def active_count(self) -> int:
            return len(self.last_activity)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a row of folders on a desk — one folder per currently running simulation — ordered left to right from longest untouched to most recently touched. Because event timestamps never go backwards, any simulation that starts or pings right now automatically gets the newest timestamp on the desk, so you simply pull its folder out and place it at the far right end! When a simulation finishes ("end"), you remove its folder completely. And when checking which runs have been silent strictly longer than timeout (current_time - last_activity > timeout), you only ever inspect the leftmost folder: pop folders from the left while they are expired, and stop the instant the leftmost folder is still within timeout because every folder to its right was touched even more recently.

Why do simpler designs fall short? Keeping an unordered dictionary and scanning all n active simulations on every call costs O(n) time per event — far too slow when 100,000 concurrent runs emit millions of pings. Even a min-heap (a binary tree in an array that exposes its smallest item at index 0 in O(log H) time) does extra work here: because you cannot cheaply reposition a node inside a heap on every ping, you must push duplicate entries and skip stale ones later, paying O(log H) time and holding stale entries in RAM. Python's OrderedDict — a hash table wired to a doubly linked list (a chain of nodes with prev/next links so any node can be unlinked or moved to the back in O(1) time, just like an LRU cache) — gives O(1) updates and zero stale entries!

Let's trace the first 5 events of Example 1 with timeout = 5 (oldest on the left, newest on the right):

1. ("sim_x", "start", 10) -> [sim_x:10]                      10 - 10 = 0 <= 5            -> []
2. ("sim_y", "start", 12) -> [sim_x:10, sim_y:12]            12 - 10 = 2 <= 5            -> []
3. ("sim_x", "ping",  14) -> [sim_y:12, sim_x:14]            sim_x moves to back         -> []
4. ("sim_z", "start", 19) -> [sim_y:12, sim_x:14, sim_z:19]  19 - 12 = 7 > 5 (pop sim_y);
                                                             19 - 14 = 5 <= 5 (stop!)    -> ["sim_y"]
5. ("sim_z", "ping",  20) -> [sim_x:14, sim_z:20]            20 - 14 = 6 > 5 (pop sim_x) -> ["sim_x"]

Complexity

Let n be the number of currently active simulations, k be the number of newly expired simulation IDs returned by the current call, and m be the total number of events processed over time.

  • Time per process_event: O(1 + k) average (O(1) amortized — meaning the average cost per event across m events is constant). Updating or removing sim_id in OrderedDict takes O(1) average hash-table + linked-list work, and _expire performs one O(1) front peek that terminates the loop plus k O(1) front pops. Because each started run enters the queue once and is popped at most once, total pops across m events never exceed m.
  • Time for is_active and active_count: O(1) average hash membership check and O(1) length lookup.
  • Space complexity: O(n). Both closed and expired runs are removed immediately from self.last_activity, keeping memory bounded strictly by live concurrent runs rather than growing forever in a long-lived service.

Edge cases

  • Silent for exactly timeout (now - last == timeout): Still alive because expiration uses strict >. In Example 1 (timeout = 5, sim_x touched at 14), t = 19 leaves sim_x active while t = 20 expires it.
  • Zero threshold (timeout = 0): Valid boundary — runs survive other events at the exact same timestamp (now - last == 0) and expire on the very next strictly larger timestamp.
  • Activity arriving after a long quiet gap for that same sim_id: Because _apply runs ahead of _expire, a "ping" refreshes its own run before the sweep and an "end" closes it cleanly without reporting an expiration, while any other stale runs expire on that call.
  • Late "ping" or "end" after expiration or normal "end": sim_id is absent from self.last_activity, so the call is ignored — an expired run is never revived or reported twice.
  • Restarting a finished sim_id: A fresh "start" inserts sim_id at the back as an independent new run.
  • Mixed sim_id types (e.g., 7 and "a"): OrderedDict hashes keys without comparing id_1 < id_2, avoiding TypeError.
  • Unrecognized event type or decreasing timestamp: Checked before mutating self.current_time or self.last_activity, keeping state completely intact.

Common mistakes

  • Assigning self.last_activity[sim_id] = timestamp without move_to_end(sim_id): Overwriting an existing key's value in OrderedDict leaves its linked-list node near the front, causing a freshly pinged run to be falsely expired or block older runs behind it!
  • Checking >= instead of >: now - oldest_time >= self.timeout prematurely expires runs whose idle duration equals timeout.
  • Maintaining a permanent expired_ids set: Saving every historical expired ID to reject late pings leaks memory unboundedly in a long-lived daemon; checking sim_id not in self.last_activity gives the exact same behavior in O(n) live space.
  • Updating self.current_time before validating inputs: If process_event("sim_x", "bad_kind", 999999) mutates self.current_time before raising ValueError, every subsequent valid call at normal timestamps falsely fails the monotonic check.
  • Pushing (timestamp, sim_id) tuples into heapq without a tie-breaker: Equal timestamps force Python to compare sim_id values directly, raising TypeError when strings and integers mix. Always include a unique monotonic counter (timestamp, seq, sim_id).

Alternative approaches

  • Hash map + min-heap with lazy deletion (O(log H) per event): Needed whenever expiration order differs from touch order (such as per-simulation custom thresholds). Lazy deletion pushes a fresh (deadline, seq, sim_id) tuple on every ping instead of mutating old heap entries in place, ignoring outdated tuples when popped if seq != latest.get(sim_id).
  • Balanced binary search tree (SortedList / TreeMap): Keeps exactly one (last_activity, seq, sim_id) entry per active run, removing the old tuple and inserting the new tuple in O(log n) worst-case time while keeping space strictly O(n).
  • Hierarchical timing wheel: Hashes runs into circular array buckets indexed by integer timestamp ticks, sweeping expired slots in O(1) per tick when timestamps advance smoothly.

Follow-up questions

  • How would the data structures change if every simulation declared its own custom timeout threshold upon starting? A run touched at t = 14 with timeout = 2 (deadline 16) expires sooner than one touched at t = 10 with timeout = 10 (deadline 20), so touch order no longer matches expiration order! Replace OrderedDict with a min-heap using lazy deletion (or a balanced BST) keyed by (timestamp + timeout_i, seq, sim_id) alongside an active dictionary storing each run's timeout_i and latest seq, achieving O(log H) (or O(log n)) per event.
  • How could the service report expired simulations promptly during quiet intervals when no new events arrive? Add a background timer task driven by a monotonic clock (time.monotonic()). Have the timer sleep until the earliest active deadline (oldest_time + timeout + 1), wake to run _expire(clock_now) and emit any expired IDs, and guard self.last_activity with a mutex (or route both incoming events and timer ticks through a single-threaded event loop).
  • How would you adapt this design if network delays caused events to arrive slightly out of timestamp order? Track a watermark — a delayed progress clock watermark = max_timestamp_seen - max_lateness guaranteeing that nearly all packets older than watermark have already arrived. Hold active runs in a deadline min-heap where each ping updates last_activity[sim_id] = max(last_activity[sim_id], event.timestamp) (so a delayed packet never overwrites a newer ping), and trigger expirations only when watermark - last_activity > timeout.

Follow-up questions

Similar questions

More Applied Intuition interview questions

All 48 Applied Intuition questions →