Coding questions · Applied Intuition
Track simulations and report timeouts
This question evaluates competency in algorithms and data-structure design for real-time stream processing, including maintaining per-simulation state, handling time-based expirations, and reasoning about performance and correctness.
You are implementing a monitoring component for many concurrent simulations.
Each simulation produces a stream of event objects of the form:
sim_id(string or integer): identifies the simulationtype(string): one of"start","ping", or"end"timestamp(integer or long): the event time in seconds (or milliseconds), monotonically non-decreasing across all events
Semantics:
start: the simulationsim_idhas started at thistimestamp. Its last activity timestamp becomes thistimestamp.ping: the simulationsim_idis still running; update its last activity timestamp to thistimestamp.end: the simulationsim_idhas finished normally at thistimestamp; after this it should no longer be considered active.
You are also given a timeout limit T (e.g., 3 seconds). A simulation should be considered timed out and automatically ended if:
\text{current_time} - \text{last\_activity\_timestamp(sim)} > T
where current_time is the timestamp of the most recently processed event.
Design a function with the following behavior:
- The function receives events one by one in time order:
processEvent(event). - Upon receiving a new event with timestamp
ts_current, it should:- Update internal state according to the event (
start,ping, orend). - Determine which simulations have just become timed out at or before
ts_current, i.e., simulations that:- Have not already ended (neither by
endevent nor by a previous timeout), and - Satisfy
ts_current - last_activity_timestamp > T.
- Have not already ended (neither by
- Mark these simulations as ended due to timeout so they will not be returned again.
- Return the set (or list) of all
sim_ids that are now considered timed out.
- Update internal state according to the event (
Your function should be efficient for large numbers of simulations and events (aim for close to time per event, where is the number of active simulations).
Specify the data structures you would use, and describe the key operations your implementation must support (no need to provide full code). Assume the process is long-running and must handle many events over time without restarting.
Track Simulation Timeouts
Examples
Example 1
Input: ([("a","start",0),("b","start",1),("b","ping",3),("c","start",5)], 3)
Output: [['a', 5]]
Explanation: Simulation a times out when current time reaches 5.
Example 2
Input: ([("a","start",0),("a","end",2),("b","start",10)], 3)
Output: []
Explanation: Ended simulations are not timed out.
Hints
- Clarify edge cases before coding.
- Keep the return value deterministic.