KatInterview

Driver Earnings Calculator with Time Overlap Handling

SQL & DataModel answer
MediumModel answerSQL & Datadata-validationtime-intervalsaggregation

Last updated

Build a pay calculator that validates delivery records, merges overlapping time windows, and computes driver earnings using configurable rate rules.

You're building a payment system for a delivery platform. Given a collection of completed delivery records and a set of compensation rules, calculate the total earnings for each driver.

Input Format

Each delivery record contains:

  • driverId: unique identifier for the driver (required, non-empty string)
  • startTime: when the driver picked up the order (required, ISO-8601 timestamp)
  • endTime: when the driver completed delivery (required, ISO-8601 timestamp)
  • miles: distance traveled in miles (required, non-negative number)
  • tip: customer tip in dollars (optional, defaults to 0)
  • incentive: platform bonus, either a single number or array of numbers (optional, defaults to 0)

The compensation rules object specifies:

  • order_base: flat rate per completed delivery (default 0)
  • mile_rate: payment per mile driven (default 0)
  • minute_rate: payment per active minute (default 0)

Requirements

  1. Validation: Reject records with missing required fields, invalid timestamps, negative values, end before start, or type mismatches. Collect all validation errors with their positions rather than stopping at the first failure.

  2. Time Calculation: When a driver handles multiple concurrent deliveries (overlapping time windows), count each minute of wall-clock time once. For example, two orders from 2:00-2:30 PM should count as 30 active minutes, not 60.

  3. Grouping: Aggregate earnings by driver and by calendar day (based on pickup time). Output should be sorted by driver ID, then by date.

  4. Precision: Use decimal arithmetic to avoid floating-point errors. Round the final total for each driver-day to the nearest cent.

  5. Testing: Provide test cases covering at least three different rate configurations, including edge cases like zero-duration deliveries, midnight crossings, and concurrent orders.

What to Deliver

Implement the calculator in SQL or Python. Explain your approach to interval merging, validation strategy, and how you handle monetary calculations. Discuss any assumptions you make about ambiguous scenarios.

Hints

Hint 1

Consider sorting time intervals by start time before merging overlapping periods

Hint 2

Handle monetary values with a decimal type to prevent rounding errors during accumulation

Hint 3

Think about whether tips and distance should be counted per-order or adjusted for overlaps