Compute Aggregate Distance Tolls for Interleaved Logs
Arrays & HashingAuto-graded · 22 test casesLast updated
Process interleaved time-ordered scanner events to compute cumulative segment-based charges across all entities.
An automated highway tracking network records passing vehicles at various fixed measurement points along a single linear road. Each measurement point is identified by a unique ID and corresponds to a specific distance position (in miles) along the highway.
You are provided with a chronologically ordered sequence of scan logs recorded throughout a day. Entries for different vehicles are interleaved within this single sequence according to time.
Every time a specific vehicle is observed at a new point immediately following its previous observation point, it completes a journey leg. The fee for that leg is calculated as:
$$\text{leg_fee} = |\text{current_location} - \text{previous_location}| \times \text{rate_per_mile}$$
Compute the total fees collected across all vehicles for the entire day, adhering to these rules:
- Fees are assessed on every consecutive pair of observations for a vehicle independently. Backtracking or visiting previous checkpoints does not offset prior charges.
- If a vehicle is detected at the exact same location consecutively, the distance traveled is
0miles, resulting in zero fee for that leg. - Vehicles observed only once throughout the day do not complete any legs and incur no fees.
Constraints
0 <= len(logs) <= 1000001 <= len(checkpoint_distances) <= 10001 <= rate_per_mile <= 100- All location IDs in
logsare present incheckpoint_distances. - Timestamps in
logsappear in non-decreasing order. - Vehicle IDs are non-empty alphanumeric strings.
Examples
Example 1
Input: calculate_total_toll([[100, 'CAR_A', 'CP_1'], [110, 'CAR_B', 'CP_2'], [130, 'CAR_A', 'CP_3'], [150, 'CAR_B', 'CP_1'], [180, 'CAR_A', 'CP_1']], {'CP_1': 10, 'CP_2': 25, 'CP_3': 40}, 2)
Output: 150
Example 2
Input: calculate_total_toll([[10, 'CAR_X', 'CP_1'], [20, 'CAR_Y', 'CP_2'], [30, 'CAR_X', 'CP_1']], {'CP_1': 5, 'CP_2': 15}, 5)
Output: 0
Hints
Hint 1
The log entries are already sorted chronologically. Does processing events out of order ever make sense?
Hint 2
What is the minimum information you need to maintain for each vehicle as you process the log stream?
Hint 3
Try maintaining a mapping from vehicle ID to its most recent recorded position.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since the log list is already chronologically ordered, we can process the entries in a single pass from left to right. Although events from different vehicles are interleaved, the order of events for any individual vehicle remains strictly chronological.
We maintain a hash table mapping each vehicle_id to its most recent known mile marker position. For each log entry (timestamp, vehicle_id, point_id):
- Lookup the mile marker position corresponding to
point_idincheckpoint_distances. - Check if
vehicle_idis present in our hash table.- If it is, calculate the distance between the current position and the previous position (
abs(curr_pos - prev_pos)). Multiply this distance byrate_per_mileand add it to a running total. - If it is not present, this is the vehicle's initial appearance, so no leg fee is charged yet.
- If it is, calculate the distance between the current position and the previous position (
- Update the hash table so that
vehicle_idpoints to thecurr_pos.
Complexity
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the number of logs. We iterate through the log list once, performing $\mathcal{O}(1)$ dictionary lookups and updates per entry.
- Space Complexity: $\mathcal{O}(V)$, where $V$ is the number of distinct vehicles seen. In the worst case, $V \le N$, requiring space to store the last known position for each vehicle in the hash map.
Python Reference Solution
from typing import List, Tuple, Dict
def calculate_total_toll(
logs: List[Tuple[int, str, str]],
checkpoint_distances: Dict[str, int],
rate_per_mile: int
) -> int:
recent_positions: Dict[str, int] = {}
accumulated_fees = 0
for _, vehicle_id, point_id in logs:
curr_pos = checkpoint_distances[point_id]
if vehicle_id in recent_positions:
prev_pos = recent_positions[vehicle_id]
accumulated_fees += abs(curr_pos - prev_pos) * rate_per_mile
recent_positions[vehicle_id] = curr_pos
return accumulated_fees