Count completed car journeys from sensor logs
Company: SoFi
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Quick Answer: This question evaluates stateful event-stream processing and per-entity state management, testing the ability to track and reconcile time-ordered sensor events while handling edge cases like unmatched or spurious events.
Constraints
- 0 <= len(logs) <= 200000
- Each log entry is (timestamp, sensor_type, car_id), with strictly increasing integer timestamps
- sensor_type is one of "ENTRY", "EXIT", or "CHECKPOINT"
Examples
Input: ([(1, "ENTRY", "A"), (2, "CHECKPOINT", "A"), (3, "EXIT", "A"), (4, "EXIT", "B"), (5, "ENTRY", "A"), (6, "ENTRY", "B"), (7, "EXIT", "B")],)
Expected Output: 2
Explanation: A completes one journey at timestamp 3. B has an unmatched EXIT at timestamp 4, then completes one journey from timestamp 6 to 7. A's second ENTRY has no EXIT, so it does not count.
Input: ([],)
Expected Output: 0
Explanation: There are no logs, so no journeys are completed.
Input: ([(1, "EXIT", "A"), (2, "ENTRY", "A"), (3, "CHECKPOINT", "A"), (4, "ENTRY", "B"), (5, "EXIT", "A"), (6, "EXIT", "C")],)
Expected Output: 1
Explanation: The first EXIT for A is ignored because A was not active yet. A then completes one journey from 2 to 5. B never exits, and C exits without entering.
Input: ([(1, "ENTRY", "X"), (2, "EXIT", "X"), (3, "ENTRY", "X"), (4, "CHECKPOINT", "X"), (5, "EXIT", "X")],)
Expected Output: 2
Explanation: Car X completes two separate journeys: 1->2 and 3->5.
Input: ([(1, "ENTRY", "A"), (2, "ENTRY", "A"), (3, "CHECKPOINT", "A"), (4, "EXIT", "A"), (5, "EXIT", "A")],)
Expected Output: 1
Explanation: The second ENTRY is ignored because A is already active. The EXIT at timestamp 4 completes one journey, and the final EXIT is ignored.
Hints
- Think about what information you need to remember for each car while scanning the logs from left to right.
- Because the logs are already time-ordered, a single pass with a hash set is enough.