Daily Driver Earnings with Time-Based Bonuses
SQL & DataModel answerLast 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 ordatetimeobject (required)end_time: ISO timestamp string ordatetimeobject (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:
- Platform pay =
(base_rate + miles × per_mile_rate) × surge_multiplier - Enforce a minimum guarantee:
max(platform_pay, min_guarantee) - Add the tip after applying the minimum (tips don't count toward the guarantee)
- 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_timeand 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
Decimalfor 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Daily Driver Earnings with Time-Based Bonuses
Clarifying Questions
Before coding, confirm these details with the interviewer:
| Aspect | Assumption |
|---|---|
| Record format | Dictionary with optional fields; missing start_time → skip |
| Minimum guarantee scope | Tips are excluded; only platform pay is subject to the floor |
| Day assignment | Calendar date extracted from start_time |
| Surge application | Multiply platform pay first, then apply minimum guarantee |
| Overlapping surge windows | Take the maximum multiplier (don't stack) |
| Invalid data | Skip the record and log index + reason; continue processing |
Key design choice: Apply the surge multiplier before enforcing the minimum. This ensures every surge delivery pays at least the minimum, and the guarantee itself isn't artificially inflated during peak hours.
Approach
This is a single-pass aggregation with per-record validation:
- Parse and validate each record: convert timestamps, coerce numeric fields, apply defaults
- Compute base platform pay:
base_rate + (miles × per_mile_rate) - Check surge eligibility: extract the time-of-day from
start_timeand find the highest matching multiplier - Apply surge and minimum:
max(platform_pay × surge, min_guarantee) - Add tip and round to cents, then accumulate into the appropriate date bucket
Surge window matching:
- Parse
"HH:MM"strings intotimeobjects for comparison - A window
[start, end)is half-open:startis included,endis not - Midnight-wrapping windows (e.g. 22:00–02:00) match when
t >= start OR t < end - If multiple windows match, use the highest multiplier
Error handling:
- Missing or invalid
start_time→ skip (can't assign to a day) - Negative miles, tip, or base_rate → skip
end_time < start_time→ skip- Non-dict records or unparseable values → skip
- Bad configuration (malformed surge windows) → fail fast with an exception
Why This Works
- Every valid delivery contributes exactly once to exactly one day
- Rounding happens per delivery, so the daily total equals the sum of individual pay statements
- The half-open interval rule prevents ambiguity at window boundaries
- Using
Decimaleliminates floating-point drift in financial calculations
Complexity
- Time: O(n · w) where n = number of deliveries, w = surge windows. Since w is constant and small (< 5 in practice), this is effectively O(n)
- Space: O(d + s) for d distinct days and s skipped records
Edge Cases to Test
- Empty or
Noneinput → empty totals - Record missing
start_time→ skipped - Negative miles or tip → skipped
- Delivery at exactly a window's end time → not surge
- Delivery at 23:30 with 22:00–02:00 window → surge applies
- Zero-mile delivery with no base_rate → uses default, then minimum applied
- Timezone-aware and naive
datetimemixed → comparison fails, record skipped
Implementation
from collections import defaultdict
from datetime import datetime, time
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
CENT = Decimal("0.01")
DEFAULT_CONFIG = {
"default_base_rate": "2.00",
"per_mile_rate": "0.50",
"min_pay_per_delivery": "3.00",
"surge_windows": [],
}
def _to_decimal(value, field, default=None):
"""Convert to Decimal with validation; raise ValueError on failure."""
if value is None or value == "":
if default is None:
raise ValueError(f"missing {field}")
return default
if isinstance(value, bool): # bool passes numeric checks but is a data bug
raise ValueError(f"{field} cannot be boolean")
try:
d = Decimal(str(value).strip())
except (InvalidOperation, ValueError):
raise ValueError(f"invalid {field}: {value!r}")
if not d.is_finite() or d < 0:
raise ValueError(f"invalid {field}: {value!r}")
return d
def _to_datetime(value, field):
"""Parse datetime from ISO string or pass through datetime object."""
if isinstance(value, datetime):
return value
if isinstance(value, str) and value.strip():
try:
return datetime.fromisoformat(value.strip())
except ValueError:
pass
raise ValueError(f"invalid {field}: {value!r}")
def _parse_surge_windows(windows):
"""Validate and parse surge config; raise on malformed input."""
parsed = []
for start_str, end_str, multiplier in windows:
start = datetime.strptime(start_str, "%H:%M").time()
end = datetime.strptime(end_str, "%H:%M").time()
mult = Decimal(str(multiplier))
if mult <= 0:
raise ValueError(f"surge multiplier must be positive: {mult}")
parsed.append((start, end, mult))
return parsed
def _get_surge_multiplier(dt, windows):
"""Find the highest surge multiplier for the given datetime."""
t = dt.time()
best = Decimal(1)
for start, end, mult in windows:
if start < end:
matches = start <= t < end
else: # wraps midnight
matches = t >= start or t < end
if matches and mult > best:
best = mult
return best
def compute_pay(deliveries, config=None):
cfg = {**DEFAULT_CONFIG, **(config or {})}
default_base = Decimal(cfg["default_base_rate"])
per_mile = Decimal(cfg["per_mile_rate"])
min_guarantee = Decimal(cfg["min_pay_per_delivery"])
surge_windows = _parse_surge_windows(cfg["surge_windows"])
daily = defaultdict(Decimal)
skipped = []
for i, rec in enumerate(deliveries or []):
try:
if not isinstance(rec, dict):
raise ValueError("not a dictionary")
start = _to_datetime(rec.get("start_time"), "start_time")
# Optional: validate end_time if present
if rec.get("end_time") not in (None, ""):
end = _to_datetime(rec["end_time"], "end_time")
if end < start:
raise ValueError("end_time before start_time")
miles = _to_decimal(rec.get("miles"), "miles", Decimal(0))
base = _to_decimal(rec.get("base_rate"), "base_rate", default_base)
tip = _to_decimal(rec.get("tip"), "tip", Decimal(0))
# Compute platform pay
platform_pay = base + (miles * per_mile)
# Apply surge multiplier
surge = _get_surge_multiplier(start, surge_windows)
platform_pay *= surge
# Enforce minimum guarantee
platform_pay = max(platform_pay, min_guarantee)
# Add tip and round
total = (platform_pay + tip).quantize(CENT, rounding=ROUND_HALF_UP)
# Accumulate by date
date_key = start.date().isoformat()
daily[date_key] += total
except (ValueError, TypeError) as e:
skipped.append({"index": i, "reason": str(e)})
return {
"daily_totals": dict(daily),
"skipped": skipped,
}
Common Mistakes
- Using
floatfor money: Leads to precision errors that compound over many deliveries - Rounding only at the end: Makes it impossible to reconcile the daily total with itemized pay stubs
- Applying minimum after adding tip: Lets tips subsidize the platform's guarantee, which is unfair to drivers
- Treating surge windows as closed intervals: Creates ambiguity when windows are adjacent (11:00–13:00 and 13:00–14:00)
- Not handling midnight wrap: A 22:00–02:00 window should match 23:00 and 01:00, but naive
start <= t < endfails
Testing Strategy
# Basic case
deliveries = [{"start_time": "2026-03-01T14:30:00", "miles": 5, "tip": 2}]
result = compute_pay(deliveries)
# Platform: 2.00 + 5×0.50 = 4.50, exceeds min, + 2 tip = 6.50
# Minimum guarantee triggered
deliveries = [{"start_time": "2026-03-01T10:00:00", "miles": 1, "tip": 1}]
# Platform: 2.00 + 1×0.50 = 2.50, raised to 3.00, + 1 tip = 4.00
# Surge with midnight wrap
config = {"surge_windows": [("22:00", "02:00", 1.5)]}
deliveries = [{"start_time": "2026-03-01T23:30:00", "miles": 3, "tip": 0}]
# Platform: (2.00 + 1.50) × 1.5 = 5.25, exceeds min = 5.25
# Invalid record
deliveries = [{"miles": 5}] # missing start_time
result = compute_pay(deliveries)
# skipped: [{"index": 0, "reason": "invalid start_time: None"}]
This solution is production-ready: it handles edge cases gracefully, uses appropriate data types for financial calculations, and surfaces errors without halting the entire batch.