My first instinct was to just count ENTRY events and call it a day, which is wrong the moment you think about interleaving.
Clarify the event semantics and journey definition, then design a state machine per vehicle using a hash map to track each vehicle's current state. Iterate through the log once, updating states and counting completed journeys when a vehicle transitions from MAINROAD to EXIT.
Pro tip: Mention that you would validate the input log for consistency (e.g., no duplicate ENTRY without EXIT) and discuss how to handle edge cases like incomplete journeys or out-of-order events, showing attention to data quality.
Ask the interviewer to confirm the definition of a complete journey (e.g., ENTRY → MAINROAD → EXIT) and whether events are guaranteed to be in chronological order per vehicle. Also clarify if a vehicle can have multiple journeys and if events can be missing.
Use a hash map (dictionary) to track each vehicle's current state, mapping vehicle ID to its last event type or a state enum. This allows O(1) updates per event and handles interleaved vehicles.
Specify valid transitions: ENTRY → MAINROAD → EXIT. Increment the journey count when a vehicle in MAINROAD state receives an EXIT event. Reset or remove the vehicle's state after a complete journey or on invalid transitions.
Loop through each event in order, update the vehicle's state in the map, and apply the counting logic. Handle edge cases like EXIT without prior ENTRY or MAINROAD by ignoring or logging errors.
State that the algorithm runs in O(n) time and O(v) space, where n is the number of events and v is the number of vehicles. Walk through a small example with interleaved events to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.