Driver Earnings Calculator with Time Overlap Handling
SQL & DataModel answerLast 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
-
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.
-
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.
-
Grouping: Aggregate earnings by driver and by calendar day (based on pickup time). Output should be sorted by driver ID, then by date.
-
Precision: Use decimal arithmetic to avoid floating-point errors. Round the final total for each driver-day to the nearest cent.
-
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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests data validation, time-interval mathematics, and careful money handling. I'll structure the solution in four phases:
1. Input Validation and Parsing
Create strict contracts for both delivery records and rate rules. Validation should be comprehensive but non-fatal: collect all errors rather than failing on the first invalid record.
For each delivery record:
- Verify all required fields are present and non-null
- Parse timestamps into datetime objects and ensure both are timezone-consistent (both naive or both aware)
- Confirm
endTimecomes afterstartTime - Convert numeric fields to
Decimalto avoid float precision issues - Handle optional fields: default missing tips to zero, sum arrays of incentives
- Reject type confusion (e.g., boolean values where numbers are expected)
For rate rules:
- Allow only known keys (
order_base,mile_rate,minute_rate) to catch typos - Default missing rates to zero
- Require non-negative finite values
Key Decision: Use Decimal(str(value)) rather than Decimal(value) directly when the input might be a float, because Decimal(0.1) preserves binary float imprecision while Decimal("0.1") represents exactly 0.1.
2. Grouping Strategy
Group validated deliveries by (driverId, day) where day is extracted from the pickup timestamp. This handles drivers working across midnight correctly: a delivery picked up at 11:50 PM and completed at 12:10 AM belongs entirely to the first day.
Use a dictionary keyed by (driverId, date_string) to accumulate deliveries efficiently.
3. Time Overlap Handling
This is the core algorithmic challenge. The question is: how do we count time when a driver carries multiple orders simultaneously?
Design Choice: Count wall-clock active time, not per-order duration. If a driver picks up order A at 2:00 PM, picks up order B at 2:10 PM, and completes both by 2:30 PM, they worked 30 minutes, not 50. This reflects the reality that the driver's time cannot be double-counted.
However, order count, mileage, tips, and incentives remain per-order. Each delivery truly happened and should be compensated.
Algorithm:
- Extract all
[startTime, endTime]intervals for the group - Sort by start time
- Merge overlapping intervals: maintain a current interval, and for each new interval, either extend the current one (if overlapping) or finalize it and start a new one
- Sum the durations of merged intervals and convert to minutes
def merge_intervals(intervals):
intervals.sort()
merged_minutes = Decimal(0)
current_start, current_end = intervals[0]
for start, end in intervals[1:]:
if start > current_end: # Gap: finalize current
merged_minutes += (current_end - current_start).total_seconds() / 60
current_start, current_end = start, end
else: # Overlap: extend current
current_end = max(current_end, end)
# Finalize last interval
merged_minutes += (current_end - current_start).total_seconds() / 60
return Decimal(str(merged_minutes))
4. Pay Calculation and Rounding
For each driver-day group:
- Order pay:
order_base × count + mile_rate × total_miles + sum(all tips and incentives) - Time pay:
minute_rate × active_minutes(from merged intervals) - Total: sum components and round once to cents using
ROUND_HALF_UP
Rounding once per group rather than per delivery avoids accumulating rounding error. If business requirements demand itemized per-order receipts, that's a one-line change, but mention this tradeoff.
Complexity
- Time: O(n log n) where n is the number of deliveries. Parsing is linear; sorting intervals within each driver-day group dominates.
- Space: O(n) for storing grouped deliveries and errors.
Edge Cases
- Validation failures: empty driver ID, timestamp format errors, timezone mismatches, negative miles, non-numeric tips
- Boundary times: deliveries that start and end at the same moment (zero duration) still earn base and distance pay
- Touching intervals: if one delivery ends at 14:30:00 and another starts at 14:30:00, they merge correctly with no double-counting
- Midnight crossing: a delivery from 23:50 to 00:10 is attributed to the pickup day
- Empty input: returns empty results with no errors
- Multiple incentives: correctly sums arrays like
[5, 10, 2.5]to 17.5
Common Mistakes
- Using float arithmetic:
0.1 + 0.2 ≠ 0.3in binary floating point. Always useDecimalfor money. - Summing per-order durations: Double-counts concurrent deliveries. Must merge intervals.
- Rounding per delivery: Accumulates rounding error. Round once per driver-day.
- Silently ignoring invalid records: Production systems need error visibility.
- Allowing unknown rate keys: A typo like
mil_ratewould silently zero out mileage pay.
Implementation Sketch
from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal, ROUND_HALF_UP
CENT = Decimal("0.01")
@dataclass(frozen=True)
class Rates:
order_base: Decimal = Decimal(0)
mile_rate: Decimal = Decimal(0)
minute_rate: Decimal = Decimal(0)
def to_decimal(val, name):
if isinstance(val, bool):
raise ValueError(f"{name} must be numeric")
try:
return Decimal(str(val))
except:
raise ValueError(f"invalid {name}: {val}")
def parse_record(raw):
# Validate required fields
driver_id = str(raw["driverId"]).strip()
if not driver_id:
raise ValueError("empty driverId")
start = datetime.fromisoformat(str(raw["startTime"]))
end = datetime.fromisoformat(str(raw["endTime"]))
if (start.tzinfo is None) != (end.tzinfo is None):
raise ValueError("timezone mismatch")
if end < start:
raise ValueError("end before start")
miles = to_decimal(raw["miles"], "miles")
tip = to_decimal(raw.get("tip") or 0, "tip")
incentive_raw = raw.get("incentive") or 0
incentives = incentive_raw if isinstance(incentive_raw, list) else [incentive_raw]
incentive_total = sum(to_decimal(x, "incentive") for x in incentives)
return {
"driver": driver_id,
"day": start.date().isoformat(),
"start": start,
"end": end,
"miles": miles,
"extras": tip + incentive_total
}
def calculate_earnings(records, rates):
groups = defaultdict(list)
errors = []
for idx, raw in enumerate(records):
try:
rec = parse_record(raw)
groups[(rec["driver"], rec["day"])].append(rec)
except Exception as e:
errors.append({"index": idx, "error": str(e)})
results = []
for (driver, day), recs in sorted(groups.items()):
# Per-order components
order_count = len(recs)
total_miles = sum(r["miles"] for r in recs)
total_extras = sum(r["extras"] for r in recs)
# Merge time intervals
intervals = [(r["start"], r["end"]) for r in recs]
active_min = merge_intervals(intervals)
# Calculate pay
pay = (rates.order_base * order_count +
rates.mile_rate * total_miles +
rates.minute_rate * active_min +
total_extras)
results.append({
"driverId": driver,
"day": day,
"earnings": pay.quantize(CENT, rounding=ROUND_HALF_UP)
})
return results, errors
This structure separates concerns cleanly: validation finds all problems upfront, grouping organizes work, interval merging handles the time complexity, and the final calculation is straightforward arithmetic with proper rounding.