KatInterview

Compute Aggregate Distance Tolls for Interleaved Logs

Arrays & HashingAuto-graded · 22 test cases
EasyAuto-gradedArrays & Hashinghash-maparraysimulation

Last 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 0 miles, 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) <= 100000
  • 1 <= len(checkpoint_distances) <= 1000
  • 1 <= rate_per_mile <= 100
  • All location IDs in logs are present in checkpoint_distances.
  • Timestamps in logs appear 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.