Courier Shift and Daily Payout Aggregation
Medium · Data Manipulation (SQL/Python) · Software Engineer · Onsite
Problem Statement
Implement a courier payout calculation module that validates rate schemas and delivery logs, handles stacked overlapping orders and midnight-crossing shifts, and outputs exact cent-rounded payouts per courier or per (courier, date).
Implement three functions:
def validate_rules(rules: Dict[str, Any]) -> Dict[str, Any]: ...
def parse_delivery(raw: Dict[str, Any]) -> Dict[str, Any]: ...
def compute_pay(
deliveries: List[Dict[str, Any]],
rules: Dict[str, Any],
by_day: bool = False,
) -> Tuple[List[Dict[str, Any]], List[Tuple[int, str]]]: ...
1. Rule Schema (validate_rules)
rulesmust be adictcontaining only keys from{"base_pay", "per_mile", "per_minute", "overlap"}; any non-dictinput or unknown key raisesValueError."base_pay","per_mile", and"per_minute"default toDecimal(0)when omitted. When present, each must be a finite non-negativeint,float, orDecimal(bool,str,None,NaN,Infinity, and negative numbers raiseValueError), returned as an exact base-10Decimal."overlap"defaults to"union"and must be either"union"or"per_delivery"(otherwise raiseValueError).
2. Delivery Record Validation (parse_delivery)
rawmust be adict(otherwise raiseValueError).- Required fields:
"dasherId","pickupTime","dropoffTime", and"distance". If any required key is omitted orNone, raiseValueError("missing <field>")."dasherId":strcontaining at least one non-whitespace character."pickupTime"and"dropoffTime": ISO 8601 timestamp strings in naive local market time (no UTC offset / timezone suffix), withdropoffTime >= pickupTime."distance": finite non-negative number (int,float, orDecimal, notboolorstr) in miles.
- Optional fields:
"tip": omitted orNonemeans0; otherwise a finite non-negative number."bonuses": omitted orNonemeans[]; otherwise alistof finite non-negative numbers."deliveryId": omitted orNonemeansNone; otherwise astrorint(notbool).
- Any field violating these rules raises
ValueErrorwith a non-empty reason string.
3. Payout Aggregation (compute_pay)
- Fail fast on bad rules: Validate
rulesfirst viavalidate_rules(rules)so invalid configuration raisesValueErrorimmediately (even ifdeliveriesis empty). - Per-record validation & deduplication: Scan
deliveriesin index order:- Skip any element where
parse_deliveryraisesValueError, recording(index, reason)inerrors. - If a valid record has a non-
None"deliveryId"that already appeared on an earlier valid record, keep the first occurrence, skip the duplicate, and record(index, f"duplicate deliveryId {delivery_id}")inerrors. Records without"deliveryId"are never deduplicated.
- Skip any element where
- Calendar grouping & overlap policies:
- Assign each valid delivery to the calendar date (
"YYYY-MM-DD") of its"pickupTime". - Within each
(dasherId, date)bucket, compute:pay = base_pay * orders + per_mile * miles + per_minute * minutes + tips + bonuses, using exact fractional minutes (seconds / 60without intermediate floating-point drift). - When
overlap == "union", count any clock interval covered by one or more concurrent orders for the same courier only once. If an order picked up on Day 1 crosses midnight into Day 2 and overlaps an order picked up on Day 2, pay the shared post-midnight span once on Day 1 (the earlier pickup date) and exclude it from Day 2. - When
overlap == "per_delivery", sum every order's individualdropoffTime - pickupTimeduration independently.
- Assign each valid delivery to the calendar date (
- Cent rounding & sorting:
- Round each
(dasherId, date)bucket once toDecimal("0.01")using half-up rounding (ROUND_HALF_UP, so$0.005 -> $0.01). - When
by_day=True, return(rows, errors)sorted lexicographically by(dasherId, date), with each row shaped as{"dasherId": str, "date": "YYYY-MM-DD", "deliveries": int, "total": Decimal}. - When
by_day=False, sum each courier's already-rounded daily rows and return(rows, errors)sorted lexicographically bydasherId, with each row shaped as{"dasherId": str, "deliveries": int, "total": Decimal}.
- Round each
Examples
Example 1
Input:
rules = {"base_pay": 2.50, "per_mile": 0.60}
deliveries = [
{"dasherId": "c2", "deliveryId": "del-1", "pickupTime": "2025-03-10T11:00:00",
"dropoffTime": "2025-03-10T11:25:00", "distance": 3.0, "tip": 4.00},
{"dasherId": "c10", "pickupTime": "2025-03-10T11:10:00",
"dropoffTime": "2025-03-10T11:40:00", "distance": 2.5},
{"dasherId": "c2", "deliveryId": "del-1", "pickupTime": "2025-03-10T11:00:00",
"dropoffTime": "2025-03-10T11:25:00", "distance": 3.0},
{"dasherId": "c1", "pickupTime": "2025-03-10T11:50:00", "distance": 1.0},
{"dasherId": "c1", "pickupTime": "2025-03-10T12:00:00",
"dropoffTime": "2025-03-10T12:20:00", "distance": 1.5, "tip": 1.50, "bonuses": [1.00]},
]
compute_pay(deliveries, rules)
Output:
(
[
{"dasherId": "c1", "deliveries": 1, "total": Decimal("5.90")},
{"dasherId": "c10", "deliveries": 1, "total": Decimal("4.00")},
{"dasherId": "c2", "deliveries": 1, "total": Decimal("8.30")},
],
[
(2, "duplicate deliveryId del-1"),
(3, "missing dropoffTime"),
],
)
Walk-through: Index 2 repeats "del-1" and index 3 omits "dropoffTime", so both are reported in errors. For valid deliveries: "c1" earns $2.50 + 1.5 * $0.60 + $1.50 + $1.00 = $5.90, "c10" earns $2.50 + 2.5 * $0.60 = $4.00, and "c2" earns $2.50 + 3.0 * $0.60 + $4.00 = $8.30, sorted as strings ("c1", "c10", "c2").
Example 2
Input:
deliveries = [
{"dasherId": "c5", "pickupTime": "2025-03-11T17:00:00",
"dropoffTime": "2025-03-11T17:30:00", "distance": 2.0, "tip": 2.00},
{"dasherId": "c5", "pickupTime": "2025-03-11T17:20:00",
"dropoffTime": "2025-03-11T17:50:00", "distance": 1.5, "bonuses": [1.25]},
{"dasherId": "c5", "pickupTime": "2025-03-11T17:35:00",
"dropoffTime": "2025-03-11T17:45:00", "distance": 0.5},
]
compute_pay(deliveries, {"base_pay": 1.50, "per_mile": 0.50, "per_minute": 0.20, "overlap": "union"})
compute_pay(deliveries, {"base_pay": 1.50, "per_mile": 0.50, "per_minute": 0.20, "overlap": "per_delivery"})
Output:
# overlap == "union":
([{"dasherId": "c5", "deliveries": 3, "total": Decimal("19.75")}], [])
# overlap == "per_delivery":
([{"dasherId": "c5", "deliveries": 3, "total": Decimal("23.75")}], [])
Walk-through: Non-time components total 3 * $1.50 + 4.0 * $0.50 + $2.00 + $1.25 = $9.75. Under "union", the three overlapping orders span a continuous 50-minute window (17:00 to 17:50), adding 50 * $0.20 = $10.00 ($19.75 total). Under "per_delivery", individual durations sum to 30 + 30 + 10 = 70 minutes, adding 70 * $0.20 = $14.00 ($23.75 total).
Example 3
Input:
rules = {"base_pay": 1.00, "per_minute": 0.12}
deliveries = [
{"dasherId": "c8", "pickupTime": "2025-03-14T23:45:00",
"dropoffTime": "2025-03-15T00:15:00", "distance": 0},
{"dasherId": "c8", "pickupTime": "2025-03-15T00:05:00",
"dropoffTime": "2025-03-15T00:25:30", "distance": 0},
]
compute_pay(deliveries, rules, by_day=True)
compute_pay(deliveries, rules, by_day=False)
Output:
# by_day=True:
(
[
{"dasherId": "c8", "date": "2025-03-14", "deliveries": 1, "total": Decimal("4.60")},
{"dasherId": "c8", "date": "2025-03-15", "deliveries": 1, "total": Decimal("2.26")},
],
[],
)
# by_day=False:
([{"dasherId": "c8", "deliveries": 2, "total": Decimal("6.86")}], [])
Walk-through: Order 1 belongs to 2025-03-14 and covers 30 active minutes ($1.00 + 30 * $0.12 = $4.60). Order 2 belongs to 2025-03-15; because 00:05:00–00:15:00 was already paid on 2025-03-14, only 00:15:00–00:25:30 (10.5 minutes) is newly active, yielding $1.00 + 10.5 * $0.12 = $2.26. Summing both daily totals gives $6.86.
Constraints
0 <= len(deliveries) <= 10^5.- All monetary and distance values are finite non-negative numbers; boolean and string values in numeric fields are invalid.
- Timestamps use naive ISO 8601 local calendar format (
YYYY-MM-DDTHH:MMorYYYY-MM-DDTHH:MM:SS[.ffffff]) without UTC offsets. - All currency rounding uses exact base-10
ROUND_HALF_UPtoDecimal("0.01").
Step-by-step walkthrough
Pin down the schema and business rules
Payroll bugs happen when edge-case policies are left vague, so define the exact input schema, output shape, and business rules up front:
Input delivery dict: { "dasherId": "c5", # required, non-empty str "deliveryId": "del-1", # optional, str or int (deduplicates retries) "pickupTime": "2025-03-11T17:00:00", # required, ISO 8601 local market time (no UTC offset) "dropoffTime": "2025-03-11T17:30:00", # required, dropoffTime >= pickupTime "distance": 2.0, # required, miles >= 0 "tip": 2.0, # optional, >= 0 (missing or None -> 0) "bonuses": [1.25] # optional, list of >= 0 (missing or None -> []) } Input rules dict: { "base_pay": 1.5, # optional >= 0, default 0 (paid per valid order) "per_mile": 0.5, # optional >= 0, default 0 "per_minute": 0.2, # optional >= 0, default 0 "overlap": "union" # optional: "union" (default) or "per_delivery" }Open question Policy in this solution Overlapping orders "union"(default): pay each active clock minute once even if 2+ orders are on board."per_delivery": sum each order's full durationMidnight-spanning orders Assigned to the date of pickupTime. Under"union", minutes shared with a post-midnight order are paid once, on the earlier pickup dateRounding to cents Exact Decimalmath, rounded half up ($0.005 -> $0.01) once per(dasherId, day); a dasher's shift total is the sum of those rounded daily totals so reports always reconcileBad records vs. bad rules A malformed or duplicate delivery is skipped and appended to errorsas(index, reason)so one bad event does not halt payroll; malformedrulesraiseValueErrorimmediatelyOutput sort order Sorted by dasherIdas strings ("d1" < "d10" < "d2"), thendate("YYYY-MM-DD")Convert money safely with exact Decimal math
Standard binary floating-point numbers (
float) cannot represent most decimal fractions accurately: in Python,0.1 + 0.2evaluates to0.30000000000000004, andround(1.005, 2)returns1.0instead of1.01both because1.005is stored slightly below1.005in binary and becauseround()uses round-half-to-even rather than standard payroll round-half-up.Convert every number using
Decimal(str(value))so0.1becomes the exact decimalDecimal("0.1"). Also guardisinstance(value, bool)explicitly first—in Python,boolis a subclass ofint, soisinstance(True, int)isTrue!from typing import Any, Dict, List, Tuple from datetime import datetime, timedelta from decimal import Decimal, InvalidOperation, ROUND_HALF_UP CENT = Decimal("0.01") MICROS_PER_MINUTE = Decimal(60_000_000) RATE_KEYS = ("base_pay", "per_mile", "per_minute") OVERLAP_POLICIES = ("union", "per_delivery") REQUIRED_FIELDS = ("dasherId", "pickupTime", "dropoffTime", "distance") def _to_decimal(value: Any, name: str) -> Decimal: """Convert a non-negative number to an exact Decimal (e.g. 0.1 -> Decimal('0.1')).""" # Check bool first because bool is a subclass of int in Python (isinstance(True, int) is True). if isinstance(value, bool) or not isinstance(value, (int, float, Decimal)): raise ValueError(f"{name} must be a number") try: # Convert via str() so float 0.1 becomes Decimal('0.1'), not binary 0.10000000000000000555... amount = value if isinstance(value, Decimal) else Decimal(str(value)) except InvalidOperation: raise ValueError(f"{name} must be a number") # Reject NaN, Infinity, and negative money/distance amounts. if not amount.is_finite() or amount < 0: raise ValueError(f"{name} must be a finite number >= 0") return amountValidate pay rules and individual delivery records
Pay rules are global configuration: if someone writes
"per_mille": 0.50by mistake, silently ignoring unknown keys would underpay every dasher.validate_rulesrejects unknown keys and converts all three rate fields intoDecimals.Individual delivery events come from external logs and retries, so
parse_deliveryvalidates one record at a time and raisesValueError("<clear reason>")socompute_paycan collect(index, reason)and keep processing the rest of the batch. Reject timestamps with UTC offsets (moment.tzinfo is not None): pay days are defined in local market time, and mixing offset-aware and naivedatetimeobjects in Python raisesTypeErrorwhen sorting intervals:def _parse_time(value: Any, name: str) -> datetime: if not isinstance(value, str): raise ValueError(f"{name} must be an ISO 8601 string") try: moment = datetime.fromisoformat(value) except ValueError: raise ValueError(f"{name} is not a valid ISO 8601 time") # Reject UTC offsets so naive and offset-aware datetimes never mix and crash sorting, # and because pay days are defined in the dasher's local market calendar. if moment.tzinfo is not None: raise ValueError(f"{name} must be local market time without a UTC offset") return moment def validate_rules(rules: Dict[str, Any]) -> Dict[str, Any]: """Check a pay-rule dict and return a clean copy with Decimal rates. Keys: base_pay, per_mile, per_minute (numbers >= 0, missing means 0) and overlap ("union" or "per_delivery", default "union"). Unknown keys raise ValueError.""" if not isinstance(rules, dict): raise ValueError("rules must be a dict") # Reject unknown keys so a typo like "per_mille" fails loudly instead of paying $0/mile. for key in rules: if key not in RATE_KEYS and key != "overlap": raise ValueError(f"unknown rule key: {key}") clean: Dict[str, Any] = {} for key in RATE_KEYS: clean[key] = _to_decimal(rules.get(key, 0), key) overlap = rules.get("overlap", "union") if overlap not in OVERLAP_POLICIES: raise ValueError(f"overlap must be one of {OVERLAP_POLICIES}") clean["overlap"] = overlap return clean def parse_delivery(raw: Dict[str, Any]) -> Dict[str, Any]: """Check one delivery record and return a clean copy; raise ValueError with the reason. Required: dasherId (non-empty str), pickupTime and dropoffTime (ISO 8601 local time, dropoff >= pickup), distance (miles >= 0). Optional: tip (default 0), bonuses (list of amounts, default []), deliveryId (str or int, used to drop duplicates).""" if not isinstance(raw, dict): raise ValueError("delivery must be a dict") # Using raw.get(key) is None treats both omitted keys and explicit JSON nulls as missing, # while keeping legitimate zero values such as distance=0. for key in REQUIRED_FIELDS: if raw.get(key) is None: raise ValueError(f"missing {key}") dasher_id = raw["dasherId"] if not isinstance(dasher_id, str) or not dasher_id.strip(): raise ValueError("dasherId must be a non-empty string") pickup = _parse_time(raw["pickupTime"], "pickupTime") dropoff = _parse_time(raw["dropoffTime"], "dropoffTime") if dropoff < pickup: raise ValueError("dropoffTime is before pickupTime") tip = raw.get("tip") if tip is None: tip = 0 bonuses = raw.get("bonuses") if bonuses is None: bonuses = [] if not isinstance(bonuses, list): raise ValueError("bonuses must be a list of amounts") bonus_total = Decimal(0) for bonus in bonuses: bonus_total += _to_decimal(bonus, "bonus") delivery_id = raw.get("deliveryId") if delivery_id is not None: if isinstance(delivery_id, bool) or not isinstance(delivery_id, (str, int)): raise ValueError("deliveryId must be a string or an integer") return { "dasherId": dasher_id, "deliveryId": delivery_id, "pickup": pickup, "dropoff": dropoff, "distance": _to_decimal(raw["distance"], "distance"), "tip": _to_decimal(tip, "tip"), "bonus": bonus_total, }Merge overlapping delivery intervals with a watermark sweep
When a dasher carries two stacked orders (
10:00–10:30and10:15–10:45), they were active on the clock for 45 minutes, not 60. Under"union", we want the total length covered by at least one[pickup, dropoff]interval.Sort the intervals by
pickuptime and sweep from left to right while trackingpaid_until(the furthest dropoff timestamp already paid). For each interval(start, end):- Clip
startup topaid_untilifstart < paid_until, because everything beforepaid_untilhas already been counted. - Only if
end > start, addend - startto the active total and advancepaid_until = end(ifend <= start, this interval sits completely inside an earlier longer order, sopaid_untilmust not move backward!).
Clock: 17:00 17:20 17:30 17:35 17:45 17:50 Order 1: [=======================] Order 2: [=================================] Order 3: [=======] (nested inside Order 2) Sweep: Order 1 (17:00-17:30): +30 min, paid_until -> 17:30 Order 2 (17:20-17:50): clipped to 17:30-17:50 -> +20 min, paid_until -> 17:50 Order 3 (17:35-17:45): clipped start=17:50 >= end=17:45 -> +0 min, paid_until stays 17:50 Total active time: 30 + 20 + 0 = 50 min (vs. 30 + 30 + 10 = 70 min per_delivery)Passing
paid_untilfrom one day of a courier into the next day handles midnight crossings automatically: if an order from23:45to00:15setspaid_until = 00:15, a next-day order from00:05to00:25:30is clipped to00:15–00:25:30(+10.5 min) instead of double-paying00:05–00:15.def _micros(start: datetime, end: datetime) -> int: # Integer microseconds avoid floating-point drift from timedelta.total_seconds(). return (end - start) // timedelta(microseconds=1) def _active_micros(deliveries: List[Dict[str, Any]], paid_until: datetime) -> Tuple[int, datetime]: """Compute active microseconds under the 'union' policy, skipping time before `paid_until` (which was already paid on an earlier day when an order crossed midnight).""" # intervals: list of (pickup_dt, dropoff_dt) sorted by earliest pickup first. intervals: List[Tuple[datetime, datetime]] = [] for delivery in deliveries: intervals.append((delivery["pickup"], delivery["dropoff"])) intervals.sort() total = 0 for start, end in intervals: # Clip any portion already covered by an earlier overlapping delivery (or yesterday's carry). if start < paid_until: start = paid_until # Guard end > start so a nested shorter delivery never moves paid_until backward. if end > start: total += _micros(start, end) paid_until = end return total, paid_until def _summed_micros(deliveries: List[Dict[str, Any]]) -> int: """Compute microseconds under 'per_delivery': sum each order's own duration independently.""" total = 0 for delivery in deliveries: total += _micros(delivery["pickup"], delivery["dropoff"]) return total- Clip
Price one dasher-day and round once at the end
Two subtle precision traps show up when pricing a day's deliveries:
- Multiply before dividing: suppose
per_minute = $0.03and active time is 50 seconds (50,000,000microseconds). The true pay is$0.03 × (50 / 60) = $0.025, which rounds half-up to$0.03. If you divide50 / 60first,0.8333333333333333333333333333 × 0.03becomes0.02499999999999999999999999999, which wrongly rounds down to$0.02! Multiplying(per_minute * micros) / 60_000_000computes1,500,000 / 60,000,000 = 0.025with zero loss. - Round once per
(dasherId, day): if three orders each earn$0.005in distance pay, their true day sum is$0.015 -> $0.02, whereas rounding each order separately would give$0.01 + $0.01 + $0.01 = $0.03.
def _group_pay(deliveries: List[Dict[str, Any]], rules: Dict[str, Any], micros: int) -> Decimal: """Compute exact pay for one (dasher, day) group and round half-up to cents once at the end.""" per_order = Decimal(0) for delivery in deliveries: per_order += rules["base_pay"] + rules["per_mile"] * delivery["distance"] per_order += delivery["tip"] + delivery["bonus"] # Multiply per_minute * micros BEFORE dividing by 60,000,000 so exact half-cents stay exact # (e.g. 50s at $0.03/min = 1.50 / 60 = 0.025 -> $0.03, instead of 0.8333... * 0.03 -> $0.02). time_pay = (rules["per_minute"] * Decimal(micros)) / MICROS_PER_MINUTE return (per_order + time_pay).quantize(CENT, rounding=ROUND_HALF_UP)- Multiply before dividing: suppose
Deduplicate, group by day, and reconcile dasher totals
compute_payties everything together in three clean phases:- Validate
rulesup front so bad configuration raisesValueErroreven on an empty delivery list. - Parse each delivery, skip invalid records or duplicate
deliveryIds while recording(index, reason)inerrors, and bucket valid deliveries by(dasherId, pickup_date_iso). - Iterate
sorted(groups). Because"YYYY-MM-DD"strings sort chronologically, each dasher's days run in exact calendar order, lettingpaid_untilcarry across midnight for that dasher and reset todatetime.minwhendasher_idchanges. Whenby_day=False,_sum_by_dashersums each dasher's rounded daily rows so daily and shift reports match to the cent.
def compute_pay(deliveries: List[Dict[str, Any]], rules: Dict[str, Any], by_day: bool = False) -> Tuple[List[Dict[str, Any]], List[Tuple[int, str]]]: """Total pay per dasher (or per dasher and day), sorted by dasherId (then date).""" # Phase 1: fail fast if the pay-rule configuration itself is invalid. clean_rules = validate_rules(rules) # Phase 2: validate each delivery, skip duplicates, and group by (dasherId, YYYY-MM-DD). # groups: maps (dasher_id, iso_date) -> list of cleaned delivery dicts. groups: Dict[Tuple[str, str], List[Dict[str, Any]]] = {} # errors: list of (input_index, reason_str) for skipped invalid or duplicate records. errors: List[Tuple[int, str]] = [] seen_ids = set() for index, raw in enumerate(deliveries): try: delivery = parse_delivery(raw) except ValueError as exc: errors.append((index, str(exc))) continue delivery_id = delivery["deliveryId"] if delivery_id is not None: if delivery_id in seen_ids: errors.append((index, f"duplicate deliveryId {delivery_id}")) continue seen_ids.add(delivery_id) pickup_date = delivery["pickup"].date().isoformat() key = (delivery["dasherId"], pickup_date) if key not in groups: groups[key] = [] groups[key].append(delivery) # Phase 3: compute rounded pay per (dasher, day) in sorted (dasherId, date) order. # Because ISO dates sort chronologically, paid_until carries cleanly across midnight # for the same dasher and resets to datetime.min whenever we move to a new dasher. day_rows: List[Dict[str, Any]] = [] previous_dasher: Any = None paid_until = datetime.min for key in sorted(groups): dasher_id, day = key if dasher_id != previous_dasher: previous_dasher = dasher_id paid_until = datetime.min day_deliveries = groups[key] if clean_rules["overlap"] == "union": micros, paid_until = _active_micros(day_deliveries, paid_until) else: micros = _summed_micros(day_deliveries) day_rows.append({ "dasherId": dasher_id, "date": day, "deliveries": len(day_deliveries), "total": _group_pay(day_deliveries, clean_rules, micros), }) if by_day: return day_rows, errors return _sum_by_dasher(day_rows), errors def _sum_by_dasher(day_rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Aggregate already-rounded day_rows per dasher so shift and daily totals always match.""" # day_rows are already sorted by dasherId, and Python dicts preserve insertion order. totals: Dict[str, Dict[str, Any]] = {} for row in day_rows: dasher_id = row["dasherId"] if dasher_id not in totals: totals[dasher_id] = { "dasherId": dasher_id, "deliveries": 0, "total": Decimal("0.00"), } totals[dasher_id]["deliveries"] += row["deliveries"] totals[dasher_id]["total"] += row["total"] return list(totals.values())- Validate
Walk through the three sample configurations
Verify the math by hand across the three examples in
statement.md:Example 1 — Base + Mileage + Tips/Bonuses (base_pay=2.50, per_mile=0.60, per_minute=0) c1 (1 valid order, 1.5 mi, tip 1.50, bonus 1.00): 2.50 + 1.5*0.60 + 2.50 = 5.90 c10 (1 valid order, 2.5 mi, no tip): 2.50 + 2.5*0.60 = 4.00 c2 (1 valid order, 3.0 mi, tip 4.00; dup skipped):2.50 + 3.0*0.60 + 4.00 = 8.30 Output order: c1, c10, c2 (lexicographic string order on dasherId) Example 2 — Overlapping Orders on c5 (base_pay=1.50, per_mile=0.50, per_minute=0.20) 17:00-17:30 (2.0 mi, tip 2.00), 17:20-17:50 (1.5 mi, bonus 1.25), 17:35-17:45 (0.5 mi) per_order = 3*1.50 + 4.0*0.50 + 2.00 + 1.25 = 9.75 overlap="union": 9.75 + 50 active min * 0.20 = 19.75 overlap="per_delivery": 9.75 + 70 summed min * 0.20 = 23.75 Example 3 — Midnight Carry with Seconds on c8 (base_pay=1.00, per_minute=0.12) 2025-03-14: 23:45:00 to 00:15:00 (30.0 min) -> 1.00 + 30.0 * 0.12 = 4.60 2025-03-15: 00:05:00 to 00:25:30 -> clipped to 10.5 min -> 1.00 + 10.5 * 0.12 = 2.26 Shift total (sum of rounded days): 4.60 + 2.26 = 6.86Complete solution
from typing import Any, Dict, List, Tuple from datetime import datetime, timedelta from decimal import Decimal, InvalidOperation, ROUND_HALF_UP CENT = Decimal("0.01") MICROS_PER_MINUTE = Decimal(60_000_000) RATE_KEYS = ("base_pay", "per_mile", "per_minute") OVERLAP_POLICIES = ("union", "per_delivery") REQUIRED_FIELDS = ("dasherId", "pickupTime", "dropoffTime", "distance") # ---- validation --------------------------------------------------------------------------- def _to_decimal(value: Any, name: str) -> Decimal: """Convert a non-negative number to an exact Decimal (e.g. 0.1 -> Decimal('0.1')).""" # Check bool first because bool is a subclass of int in Python (isinstance(True, int) is True). if isinstance(value, bool) or not isinstance(value, (int, float, Decimal)): raise ValueError(f"{name} must be a number") try: # Convert via str() so float 0.1 becomes Decimal('0.1'), not binary 0.10000000000000000555... amount = value if isinstance(value, Decimal) else Decimal(str(value)) except InvalidOperation: raise ValueError(f"{name} must be a number") # Reject NaN, Infinity, and negative money/distance amounts. if not amount.is_finite() or amount < 0: raise ValueError(f"{name} must be a finite number >= 0") return amount def _parse_time(value: Any, name: str) -> datetime: if not isinstance(value, str): raise ValueError(f"{name} must be an ISO 8601 string") try: moment = datetime.fromisoformat(value) except ValueError: raise ValueError(f"{name} is not a valid ISO 8601 time") # Reject UTC offsets so naive and offset-aware datetimes never mix and crash sorting, # and because pay days are defined in the dasher's local market calendar. if moment.tzinfo is not None: raise ValueError(f"{name} must be local market time without a UTC offset") return moment def validate_rules(rules: Dict[str, Any]) -> Dict[str, Any]: """Check a pay-rule dict and return a clean copy with Decimal rates. Keys: base_pay, per_mile, per_minute (numbers >= 0, missing means 0) and overlap ("union" or "per_delivery", default "union"). Unknown keys raise ValueError.""" if not isinstance(rules, dict): raise ValueError("rules must be a dict") # Reject unknown keys so a typo like "per_mille" fails loudly instead of paying $0/mile. for key in rules: if key not in RATE_KEYS and key != "overlap": raise ValueError(f"unknown rule key: {key}") clean: Dict[str, Any] = {} for key in RATE_KEYS: clean[key] = _to_decimal(rules.get(key, 0), key) overlap = rules.get("overlap", "union") if overlap not in OVERLAP_POLICIES: raise ValueError(f"overlap must be one of {OVERLAP_POLICIES}") clean["overlap"] = overlap return clean def parse_delivery(raw: Dict[str, Any]) -> Dict[str, Any]: """Check one delivery record and return a clean copy; raise ValueError with the reason. Required: dasherId (non-empty str), pickupTime and dropoffTime (ISO 8601 local time, dropoff >= pickup), distance (miles >= 0). Optional: tip (default 0), bonuses (list of amounts, default []), deliveryId (str or int, used to drop duplicates).""" if not isinstance(raw, dict): raise ValueError("delivery must be a dict") # Using raw.get(key) is None treats both omitted keys and explicit JSON nulls as missing, # while keeping legitimate zero values such as distance=0. for key in REQUIRED_FIELDS: if raw.get(key) is None: raise ValueError(f"missing {key}") dasher_id = raw["dasherId"] if not isinstance(dasher_id, str) or not dasher_id.strip(): raise ValueError("dasherId must be a non-empty string") pickup = _parse_time(raw["pickupTime"], "pickupTime") dropoff = _parse_time(raw["dropoffTime"], "dropoffTime") if dropoff < pickup: raise ValueError("dropoffTime is before pickupTime") tip = raw.get("tip") if tip is None: tip = 0 bonuses = raw.get("bonuses") if bonuses is None: bonuses = [] if not isinstance(bonuses, list): raise ValueError("bonuses must be a list of amounts") bonus_total = Decimal(0) for bonus in bonuses: bonus_total += _to_decimal(bonus, "bonus") delivery_id = raw.get("deliveryId") if delivery_id is not None: if isinstance(delivery_id, bool) or not isinstance(delivery_id, (str, int)): raise ValueError("deliveryId must be a string or an integer") return { "dasherId": dasher_id, "deliveryId": delivery_id, "pickup": pickup, "dropoff": dropoff, "distance": _to_decimal(raw["distance"], "distance"), "tip": _to_decimal(tip, "tip"), "bonus": bonus_total, } # ---- pay computation ---------------------------------------------------------------------- def _micros(start: datetime, end: datetime) -> int: # Integer microseconds avoid floating-point drift from timedelta.total_seconds(). return (end - start) // timedelta(microseconds=1) def _active_micros(deliveries: List[Dict[str, Any]], paid_until: datetime) -> Tuple[int, datetime]: """Compute active microseconds under the 'union' policy, skipping time before `paid_until` (which was already paid on an earlier day when an order crossed midnight).""" # intervals: list of (pickup_dt, dropoff_dt) sorted by earliest pickup first. intervals: List[Tuple[datetime, datetime]] = [] for delivery in deliveries: intervals.append((delivery["pickup"], delivery["dropoff"])) intervals.sort() total = 0 for start, end in intervals: # Clip any portion already covered by an earlier overlapping delivery (or yesterday's carry). if start < paid_until: start = paid_until # Guard end > start so a nested shorter delivery never moves paid_until backward. if end > start: total += _micros(start, end) paid_until = end return total, paid_until def _summed_micros(deliveries: List[Dict[str, Any]]) -> int: """Compute microseconds under 'per_delivery': sum each order's own duration independently.""" total = 0 for delivery in deliveries: total += _micros(delivery["pickup"], delivery["dropoff"]) return total def _group_pay(deliveries: List[Dict[str, Any]], rules: Dict[str, Any], micros: int) -> Decimal: """Compute exact pay for one (dasher, day) group and round half-up to cents once at the end.""" per_order = Decimal(0) for delivery in deliveries: per_order += rules["base_pay"] + rules["per_mile"] * delivery["distance"] per_order += delivery["tip"] + delivery["bonus"] # Multiply per_minute * micros BEFORE dividing by 60,000,000 so exact half-cents stay exact # (e.g. 50s at $0.03/min = 1.50 / 60 = 0.025 -> $0.03, instead of 0.8333... * 0.03 -> $0.02). time_pay = (rules["per_minute"] * Decimal(micros)) / MICROS_PER_MINUTE return (per_order + time_pay).quantize(CENT, rounding=ROUND_HALF_UP) def compute_pay(deliveries: List[Dict[str, Any]], rules: Dict[str, Any], by_day: bool = False) -> Tuple[List[Dict[str, Any]], List[Tuple[int, str]]]: """Total pay per dasher (or per dasher and day), sorted by dasherId (then date).""" # Phase 1: fail fast if the pay-rule configuration itself is invalid. clean_rules = validate_rules(rules) # Phase 2: validate each delivery, skip duplicates, and group by (dasherId, YYYY-MM-DD). # groups: maps (dasher_id, iso_date) -> list of cleaned delivery dicts. groups: Dict[Tuple[str, str], List[Dict[str, Any]]] = {} # errors: list of (input_index, reason_str) for skipped invalid or duplicate records. errors: List[Tuple[int, str]] = [] seen_ids = set() for index, raw in enumerate(deliveries): try: delivery = parse_delivery(raw) except ValueError as exc: errors.append((index, str(exc))) continue delivery_id = delivery["deliveryId"] if delivery_id is not None: if delivery_id in seen_ids: errors.append((index, f"duplicate deliveryId {delivery_id}")) continue seen_ids.add(delivery_id) pickup_date = delivery["pickup"].date().isoformat() key = (delivery["dasherId"], pickup_date) if key not in groups: groups[key] = [] groups[key].append(delivery) # Phase 3: compute rounded pay per (dasher, day) in sorted (dasherId, date) order. # Because ISO dates sort chronologically, paid_until carries cleanly across midnight # for the same dasher and resets to datetime.min whenever we move to a new dasher. day_rows: List[Dict[str, Any]] = [] previous_dasher: Any = None paid_until = datetime.min for key in sorted(groups): dasher_id, day = key if dasher_id != previous_dasher: previous_dasher = dasher_id paid_until = datetime.min day_deliveries = groups[key] if clean_rules["overlap"] == "union": micros, paid_until = _active_micros(day_deliveries, paid_until) else: micros = _summed_micros(day_deliveries) day_rows.append({ "dasherId": dasher_id, "date": day, "deliveries": len(day_deliveries), "total": _group_pay(day_deliveries, clean_rules, micros), }) if by_day: return day_rows, errors return _sum_by_dasher(day_rows), errors def _sum_by_dasher(day_rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Aggregate already-rounded day_rows per dasher so shift and daily totals always match.""" # day_rows are already sorted by dasherId, and Python dicts preserve insertion order. totals: Dict[str, Dict[str, Any]] = {} for row in day_rows: dasher_id = row["dasherId"] if dasher_id not in totals: totals[dasher_id] = { "dasherId": dasher_id, "deliveries": 0, "total": Decimal("0.00"), } totals[dasher_id]["deliveries"] += row["deliveries"] totals[dasher_id]["total"] += row["total"] return list(totals.values())✅ Submit now — all tests should pass.
Intuition & how it works
Picture highlighting a courier's active delivery windows along a paper timeline with a yellow marker. When "c5" carries stacked orders—such as 17:00–17:30, 17:20–17:50, and 17:35–17:45—per-order pay (base pay, miles, tips, and bonuses) applies to every order, while under active-time pay ("union") we measure the total length of yellow highlight on the timeline once (50 minutes from 17:00 to 17:50) rather than paying two or three times where strokes overlap.
A naive summation script gets payroll wrong in three places. First, summing dropoff - pickup per order double-counts overlapping minutes on stacked orders (and double-counts minutes after midnight when a late-night order crosses 00:00). Second, computing money with binary floats and Python's built-in round() introduces one-cent errors (round(1.005, 2) yields 1.0 instead of 1.01). Third, crashing on a single malformed JSON record halts an entire payroll batch, whereas silently ignoring typos in the rule schema (like "per_mille") quietly zeroes out everyone's mileage pay.
Instead, we validate the rule schema strictly, validate records individually (collecting (index, reason) errors and skipping duplicate deliveryIds), compute money using exact decimal arithmetic (base-10 Decimal numbers that represent cents without binary rounding error), and measure active time via an interval sweep (sorting intervals by start time and tracking a paid_until cursor so overlapping segments are counted only once). Walk through "c5"'s three orders above under base_pay = $1.50, per_mile = $0.50, per_minute = $0.20:
- Order 1 (
17:00–17:30,2.0mi,$2.00tip): interval sweep adds30active minutes and advancespaid_untilto17:30. - Order 2 (
17:20–17:50,1.5mi,$1.25bonus): start17:20is clipped topaid_until = 17:30, adding20new active minutes (50total) and advancingpaid_untilto17:50. - Order 3 (
17:35–17:45,0.5mi): start17:35clips to17:50 >= 17:45, adding0extra minutes while keepingpaid_untilat17:50. Exact day total:3 × $1.50(base)+ 4.0 × $0.50(miles)+ 50 × $0.20(active minutes)+ $2.00(tip)+ $1.25(bonus)= $19.75, rounded half-up to cents once at the end.
Complexity
Let n be the number of input delivery records and G be the number of distinct (dasherId, date) groups (G <= n).
- Time: O(n log n) overall. Validating the
nrecords, checkingseen_idsfor duplicates, and bucketing by(dasherId, date)takes O(n) average time using hash-table lookups; sorting theGgroup keys takes O(G log G) time; and sorting thekdelivery intervals inside each(dasherId, date)group takes O(k log k) time, which sums across all groups (sum(k) <= n) to at most O(n log n). - Space: O(n) memory, because we store at most
ncleaned delivery dictionaries acrossgroups, up tonseendeliveryIds inseen_ids, up tonerror tuples inerrors, andG <= noutput summary rows.
Edge cases
- Zero-minute handoffs (
pickupTime == dropoffTime): valid; earns base pay, distance, tips, and bonuses with0active minutes. - Touching, nested, and chained overlaps: back-to-back orders (
12:00–12:10and12:10–12:20) yield20minutes under both policies; a nested order (10:40–10:42inside10:15–10:45) contributes0extra union minutes without movingpaid_untilbackward. - Orders crossing midnight: grouped under the pickup date, while
paid_untilcarries into the same dasher's next date so post-midnight minutes shared with a morning order are paid only once (andpaid_untilresets todatetime.minwhen moving to the next dasher). - Fractional minutes and half-cent boundaries: durations are tracked in exact integer microseconds, and
(per_minute * micros) / 60_000_000multiplies before dividing so exact half-cents (such as 50 seconds at$0.03/min = $0.025) round up to$0.03. - Nulls, bad types, and duplicates: missing optional
tiporbonuses(or explicitNone) default to0and[]; strings like"3.2", booleans likeTrue, negative numbers,NaN, UTC offsets, and repeateddeliveryIds are skipped and reported inerrors. - Idempotent rule validation: passing the output of
validate_rules(Decimalrates) back intovalidate_rulesorcompute_payworks cleanly (idempotency means applying a validation or cleanup step a second time leaves the result unchanged).
Common mistakes
- Using
floatand built-inround(..., 2)for currency:floatintroduces binary representation drift, and Python'sround()uses round-half-to-even (round(0.125, 2) == 0.12) instead ofROUND_HALF_UP. - Rounding per order instead of per day: three orders with
$0.005distance pay sum to$0.015 -> $0.02for the day, whereas rounding each order first gives$0.03—and rounding shift totals independently from day totals makes daily and shift statements disagree by cents. - Unconditionally setting
paid_until = endduring the interval sweep: if(10:40, 10:42)follows(10:15, 10:45), overwritingpaid_untilwith10:42moves the cursor backward and double-pays10:42–10:45on the next order. - Resetting
paid_untilat midnight for the same dasher: double-pays minutes after00:00when a23:50–00:20delivery overlaps a00:10–00:30delivery. - Forgetting
isinstance(True, int)in Python: without an explicitisinstance(value, bool)check,"tip": Truesilently adds$1.00. - Writing
raw.get("tip", 0)when JSON contains"tip": null:dict.getreturnsNonewhen the key exists with valueNone, causing aTypeErrorlater.
Alternative approaches
- Per-order active-time splitting (event sweep line): instead of computing only the union duration for the whole day, sort all
2npickup (+1) and dropoff (-1) events and split each slice's minutes equally (slice_minutes / active_orders) across the orders currently on board; the daily total matches"union", while giving every individual order an attributed time payout. - Engaged shift span (
max(dropoff) - min(pickup)): pays idle waiting minutes between orders as well; that is a different product rule rather than a different algorithm for active delivery time.
Follow-up questions
- How would you extend the engine to support a per-order minimum payout floor alongside peak-hour rate multipliers? Enforcing a per-order minimum floor requires attributing active minutes to each individual order, so replace the day-level union sweep with an event sweep line (
+1at pickup,-1at dropoff) that splits each slice's duration equally (slice_duration / concurrent_orders) across active orders, appliesmax(order_floor, attributed_pay)per order, and sums. To layer peak-hour multipliers (such as1.5xper-minute rates between17:00and20:00), intersect each active span[start, end]against the sorted peak windows with a two-pointer scan so overlapping peak sub-spans earnper_minute * multiplierand off-peak sub-spans earnper_minute. - How could you express the
"union"active-time calculation and daily payout aggregation purely in SQL? Store monetary rates and amounts asDECIMAL/NUMERICrather thanFLOAT, and compute each row's preceding watermarkpaid_untilusing a SQL window function (an aggregate likeMAX(...) OVER (...)evaluated across ordered peer rows without collapsing them):MAX(dropoff_time) OVER (PARTITION BY dasher_id ORDER BY pickup_time, dropoff_time ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING). Partitioning solely bydasher_idcarriespaid_untilacross midnight automatically, letting each row contributeGREATEST(dropoff_time - GREATEST(pickup_time, COALESCE(paid_until, pickup_time)), INTERVAL '0 seconds')insideGROUP BY dasher_id, CAST(pickup_time AS DATE). - What architectural changes are needed when delivery events arrive continuously over an at-least-once streaming pipeline? Persist seen
deliveryIdkeys in a durable deduplication store because at-least-once brokers routinely replay events after worker restarts. Accumulate per-(dasherId, date)state behind an end-of-day watermark (a post-midnight grace window allowing delayed mobile app uploads to land) before closing the date and emitting the rounded statement; if an even later tip update or dispute adjustment arrives after settlement, write an immutable delta entry onto the current open payout cycle rather than mutating closed historical statements.
Follow-up questions
- How would you extend the engine to support a per-order minimum payout floor alongside peak-hour rate multipliers?
- How could you express the `"union"` active-time calculation and daily payout aggregation purely in SQL?
- What architectural changes are needed when delivery events arrive continuously over an at-least-once streaming pipeline?
Similar questions
- Courier Dispatch Offer Ranking and Escalation
- 30-Day Late Shipment Rate and Most Affected Customers
- Monthly Restaurant Revenue Growth
- Order Delivery and Dispatch Offer Metrics
- Daily Delivery Driver Earnings with Surge Windows
- Aggregate Courier Payouts from Paginated Events
More DoorDash interview questions
- Menu Dish Reviews, Star Ratings, and Mutable Vote Counters Medium
- Concurrent Startup Aggregator and HTTP Status Mapping Medium
- Engineering Behavioral Deep Dive: Ownership, Collaboration, and Resilience Medium Pro
- Rank Top Merchants per City by Net GMV Medium Pro
- Session Bootstrap Aggregator with Graceful Degradation Medium Pro
- FIFO Courier-to-Order Dispatch Service and Bookkeeping Invariants Medium Pro
- Courier Payout with Surge Windows Medium Pro
- Daily Delivery Driver Earnings with Surge Windows Medium Pro
- Fault-Tolerant Round-Robin Request Router Medium Pro
- High-Impact Engineering Project: Architecture, Reliability, and Hindsight Medium Pro