KatInterview

Compute Courier Compensation for Delivery Trips

Math & Bit ManipulationModel answer
MediumModel answerMath & Bit Manipulationmathparsingsimulation

Last updated

Calculate total delivery earnings from start/end times and distances using conditional rates, rush-hour multipliers, and precision rules.

You are building a compensation module for a logistics platform to evaluate total courier payouts across completed delivery orders.

Each delivery order is formatted as an object with three attributes:

  • start_time (string): The start timestamp in ISO format (e.g., "2023-11-15T17:45:00").
  • end_time (string): The completion timestamp in ISO format (e.g., "2023-11-15T18:15:00").
  • distance_km (float): The total travel distance in kilometers.

Pricing Specifications:

  1. Base Rate: Every trip earns a fixed base fee of $2.00.
  2. Mileage Fee: Add $0.50 for each completed kilometer.
  3. Trip Duration Surcharge:
    • If the delivery duration is strictly greater than 30 minutes, append a flat delay bonus of $5.00.
  4. Rush Hour Surcharge:
    • If the delivery starts during rush hour (18:00 to 21:00 inclusive), apply an extra 20% multiplier (1.20x) to the trip's subtotal (Base Rate + Mileage Fee + Duration Surcharge).

Instructions:

Write a function calculate_payout(deliveries) that accepts a list of delivery objects and returns the total courier payout as a float, rounded to two decimal places.

Rules & Constraints:

  • All timestamps within a single test case fall on the same calendar day.
  • Rush hour start condition is inclusive: any start time where 18:00:00 <= start_time <= 21:00:00 qualifies.
  • Precision requirement: Intermediate individual trip totals must be rounded to 4 decimal places before summing them up to avoid accumulation drift.
  • The returned final output must be rounded to 2 decimal places.

Example 1:

deliveries = [
    {
        "start_time": "2023-11-15T18:00:00",
        "end_time": "2023-11-15T18:40:00",
        "distance_km": 2.0
    }
]

# Step-by-step:
# Base rate = 2.00
# Mileage = 2.0 * 0.50 = 1.00
# Duration = 40 minutes (> 30 mins) -> Delay fee = 5.00
# Subtotal = 2.00 + 1.00 + 5.00 = 8.00
# Rush Hour check: Starts at 18:00:00 (In range [18:00, 21:00]) -> 8.00 * 1.20 = 9.60
# Result: 9.6

Hints

Hint 1

Parse timestamps into datetime objects and calculate duration by taking their difference in minutes.

Hint 2

Separate subtotal calculation (base + distance + duration fee) from the rush hour multiplier.

Hint 3

Use Python's `decimal` module or precise intermediate rounding to 4 decimal places before computing the overall sum.