KatInterview

Daily Driver Earnings with Time-Based Bonuses

SQL & DataModel answer
MediumModel answerSQL & Datadata-processingbusiness-logictime-windows

Last updated

Calculate a courier's total earnings per day from delivery records, applying distance rates, minimum guarantees, and optional surge multipliers for high-demand hours.

You're building a payroll module for a delivery platform. Write a function compute_pay(deliveries, config=None) that processes a list of delivery records and returns each driver's total earnings grouped by calendar day.

Each delivery record is a dictionary with these fields:

  • start_time: ISO timestamp string or datetime object (required)
  • end_time: ISO timestamp string or datetime object (optional)
  • miles: numeric distance traveled (optional, defaults to 0)
  • base_rate: platform fee in dollars (optional, uses config default if missing)
  • tip: customer tip in dollars (optional, defaults to 0)

Payment rules:

  1. Platform pay = (base_rate + miles × per_mile_rate) × surge_multiplier
  2. Enforce a minimum guarantee: max(platform_pay, min_guarantee)
  3. Add the tip after applying the minimum (tips don't count toward the guarantee)
  4. Round each delivery's total to the nearest cent before summing

Configuration (use these defaults if config is None):

{
    "default_base_rate": "2.00",
    "per_mile_rate": "0.50",
    "min_pay_per_delivery": "3.00",
    "surge_windows": []  # list of ("HH:MM", "HH:MM", multiplier)
}

Surge windows (follow-up): Each tuple defines a half-open interval [start, end). If a delivery's start_time falls within the window (by wall-clock hour:minute), multiply the platform pay by the given factor before applying the minimum. Windows where start > end (e.g. ("22:00", "02:00", 1.5)) wrap around midnight. If multiple windows overlap, use the highest multiplier.

Error handling:

  • Skip any record with a missing or unparseable start_time and log it
  • Skip records with negative values, non-numeric fields, or end_time < start_time
  • Return {"daily_totals": {date_string: amount}, "skipped": [{"index": i, "reason": msg}]}

Additional requirements:

  • Use Decimal for all monetary arithmetic to avoid floating-point errors
  • Group deliveries by the calendar date of start_time (format "YYYY-MM-DD")
  • A delivery starting at 23:50 on March 1 and ending at 00:10 on March 2 belongs to March 1

Hints

Hint 1

Think about the order of operations: surge multiplier, then minimum, then add tip. Why does that order matter for fairness?

Hint 2

A time window like 22:00–02:00 matches times that satisfy (t >= 22:00) OR (t < 02:00). Test midnight-crossing cases.

Hint 3

Use Decimal for every calculation and round once per delivery, not once at the end, so individual pay stubs match the daily total.