Count Complete Highway Journeys from Toll Logs
OnepaySoftware Engineer · Technical ScreenLast updated
This problem tests string manipulation, hash map usage, and state tracking to identify valid entry-to-exit sequences from an unordered stream of toll logs.
Problem Statement
You are given a list of toll records for vehicles on a highway. Each record contains a vehicle_id, a location_id, and a timestamp. A complete journey is defined as a vehicle passing an 'ENTRY' gate followed by an 'EXIT' gate.
Given an unsorted list of records, identify all completed journeys. A journey is valid only if:
- The
vehicle_idmatches for both records. - The
ENTRYtimestamp is strictly less than theEXITtimestamp. - There are no other records for the same
vehicle_idbetween these two timestamps.
Write a function count_completed_journeys(records) that returns the total count of such valid journeys.
Input Format
records is a list of dictionaries: {'vehicle_id': str, 'type': 'ENTRY' | 'EXIT', 'timestamp': int}
Constraints
1 <= records.length <= 10^5- Timestamps are unique within a vehicle's history.
Example
# Input:
records = [
{'vehicle_id': 'A', 'type': 'ENTRY', 'timestamp': 10},
{'vehicle_id': 'A', 'type': 'EXIT', 'timestamp': 20},
{'vehicle_id': 'B', 'type': 'ENTRY', 'timestamp': 5},
{'vehicle_id': 'B', 'type': 'ENTRY', 'timestamp': 15},
{'vehicle_id': 'B', 'type': 'EXIT', 'timestamp': 25}
]
# Output: 2
# Explanation: 'A' has one valid ENTRY-EXIT pair. 'B' has one valid pair (15, 25),
# as (5, 25) is invalid because there is an entry at 15 in between.
Hints
Hint 1
Sort the records for each vehicle individually by timestamp.
Hint 2
Once sorted, a valid journey is simply a sequence where an ENTRY is immediately followed by an EXIT.
Hint 3
Use a dictionary to group records by vehicle_id before processing the sequences.
Follow-up questions
- How would you modify your solution if the input arrives as a continuous stream rather than a static list?
- How would you handle a scenario where an EXIT is recorded but the system failed to log the corresponding ENTRY (i.e., 'dangling' exits)?
- If memory is a constraint, how would you store the state for millions of vehicles currently on the road?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.