Implement Journey Counter and Speeder Detector
HeadwaySoftware Engineer · Technical ScreenLast updated
This problem tests your ability to process time-series event data by grouping related actions, managing state across sequences, and performing geometric or threshold-based calculations.
Problem Statement
You are provided with a stream of toll booth logs representing vehicles moving through a series of checkpoints. Each log entry is a string in the format: "vehicle_id,checkpoint_id,timestamp_in_seconds".
Your task is to identify "speeding journeys." A journey is defined as a sequence of logs for the same vehicle starting at checkpoint_A and ending at checkpoint_B (where A < B). A speeding violation occurs if the average speed between two consecutive checkpoints in a journey exceeds a given speed_limit. The distance between checkpoint_i and checkpoint_{i+1} is defined as 10 kilometers.
Implement the class SpeedTracker:
class SpeedTracker:
def __init__(self, speed_limit):
# Initialize with max speed in km/s
pass
def process_logs(self, logs):
# logs: list of strings
# Returns a list of vehicle_ids that committed at least one speeding violation
pass
Constraints
timestampis an integer representing seconds since the start of the day.checkpoint_idis an integer; a journey is only valid if the vehicle passes checkpoints in strictly increasing numerical order.- A vehicle might pass multiple checkpoints; calculate speed between every consecutive pair.
Example
Logs: ["V1,1,100", "V1,2,150", "V1,3,170"], speed_limit = 0.15 km/s.
- Journey V1:
- 1 to 2: Distance 10, Time 50s. Speed = 10/50 = 0.2 km/s (Speeding!)
- 2 to 3: Distance 10, Time 20s. Speed = 10/20 = 0.5 km/s (Speeding!)
- Output:
["V1"]
Edge Cases
- A vehicle passes a checkpoint with a lower ID than the previous one (invalidates the journey state for that vehicle).
- Multiple journeys for the same vehicle ID (e.g., V1 finishes at 3, then starts again at 1).
Hints
Hint 1
Use a dictionary to map each vehicle_id to its most recent checkpoint_id and its corresponding timestamp.
Hint 2
When processing a new log entry, verify if the new checkpoint_id is greater than the stored one; if not, reset or treat as a new journey.
Hint 3
Maintain a set of speeding vehicles to ensure each ID is only reported once, regardless of the number of violations.
Follow-up questions
- How would you modify your solution to handle unordered log entries within a specific window of time?
- What changes are needed if the distance between checkpoints is not uniform, but provided as a lookup table?
- How would you optimize the memory usage if you had to process logs for millions of vehicles over a 24-hour period?
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.