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)

  • rules must be a dict containing only keys from {"base_pay", "per_mile", "per_minute", "overlap"}; any non-dict input or unknown key raises ValueError.
  • "base_pay", "per_mile", and "per_minute" default to Decimal(0) when omitted. When present, each must be a finite non-negative int, float, or Decimal (bool, str, None, NaN, Infinity, and negative numbers raise ValueError), returned as an exact base-10 Decimal.
  • "overlap" defaults to "union" and must be either "union" or "per_delivery" (otherwise raise ValueError).

2. Delivery Record Validation (parse_delivery)

  • raw must be a dict (otherwise raise ValueError).
  • Required fields: "dasherId", "pickupTime", "dropoffTime", and "distance". If any required key is omitted or None, raise ValueError("missing <field>").
    • "dasherId": str containing at least one non-whitespace character.
    • "pickupTime" and "dropoffTime": ISO 8601 timestamp strings in naive local market time (no UTC offset / timezone suffix), with dropoffTime >= pickupTime.
    • "distance": finite non-negative number (int, float, or Decimal, not bool or str) in miles.
  • Optional fields:
    • "tip": omitted or None means 0; otherwise a finite non-negative number.
    • "bonuses": omitted or None means []; otherwise a list of finite non-negative numbers.
    • "deliveryId": omitted or None means None; otherwise a str or int (not bool).
  • Any field violating these rules raises ValueError with a non-empty reason string.

3. Payout Aggregation (compute_pay)

  1. Fail fast on bad rules: Validate rules first via validate_rules(rules) so invalid configuration raises ValueError immediately (even if deliveries is empty).
  2. Per-record validation & deduplication: Scan deliveries in index order:
    • Skip any element where parse_delivery raises ValueError, recording (index, reason) in errors.
    • 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}") in errors. Records without "deliveryId" are never deduplicated.
  3. 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 / 60 without 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 individual dropoffTime - pickupTime duration independently.
  4. Cent rounding & sorting:
    • Round each (dasherId, date) bucket once to Decimal("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 by dasherId, with each row shaped as {"dasherId": str, "deliveries": int, "total": Decimal}.

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:MM or YYYY-MM-DDTHH:MM:SS[.ffffff]) without UTC offsets.
  • All currency rounding uses exact base-10 ROUND_HALF_UP to Decimal("0.01").

Step-by-step walkthrough

  1. 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 duration
    Midnight-spanning orders Assigned to the date of pickupTime. Under "union", minutes shared with a post-midnight order are paid once, on the earlier pickup date
    Rounding to cents Exact Decimal math, 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 reconcile
    Bad records vs. bad rules A malformed or duplicate delivery is skipped and appended to errors as (index, reason) so one bad event does not halt payroll; malformed rules raise ValueError immediately
    Output sort order Sorted by dasherId as strings ("d1" < "d10" < "d2"), then date ("YYYY-MM-DD")
  2. Convert money safely with exact Decimal math

    Standard binary floating-point numbers (float) cannot represent most decimal fractions accurately: in Python, 0.1 + 0.2 evaluates to 0.30000000000000004, and round(1.005, 2) returns 1.0 instead of 1.01 both because 1.005 is stored slightly below 1.005 in binary and because round() uses round-half-to-even rather than standard payroll round-half-up.

    Convert every number using Decimal(str(value)) so 0.1 becomes the exact decimal Decimal("0.1"). Also guard isinstance(value, bool) explicitly first—in Python, bool is a subclass of int, so isinstance(True, int) is True!

    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 amount
    
  3. Validate pay rules and individual delivery records

    Pay rules are global configuration: if someone writes "per_mille": 0.50 by mistake, silently ignoring unknown keys would underpay every dasher. validate_rules rejects unknown keys and converts all three rate fields into Decimals.

    Individual delivery events come from external logs and retries, so parse_delivery validates one record at a time and raises ValueError("<clear reason>") so compute_pay can 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 naive datetime objects in Python raises TypeError when 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,
        }
    
  4. Merge overlapping delivery intervals with a watermark sweep

    When a dasher carries two stacked orders (10:00–10:30 and 10: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 pickup time and sweep from left to right while tracking paid_until (the furthest dropoff timestamp already paid). For each interval (start, end):

    1. Clip start up to paid_until if start < paid_until, because everything before paid_until has already been counted.
    2. Only if end > start, add end - start to the active total and advance paid_until = end (if end <= start, this interval sits completely inside an earlier longer order, so paid_until must 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_until from one day of a courier into the next day handles midnight crossings automatically: if an order from 23:45 to 00:15 sets paid_until = 00:15, a next-day order from 00:05 to 00:25:30 is clipped to 00:15–00:25:30 (+10.5 min) instead of double-paying 00: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
    
  5. Price one dasher-day and round once at the end

    Two subtle precision traps show up when pricing a day's deliveries:

    1. Multiply before dividing: suppose per_minute = $0.03 and active time is 50 seconds (50,000,000 microseconds). The true pay is $0.03 × (50 / 60) = $0.025, which rounds half-up to $0.03. If you divide 50 / 60 first, 0.8333333333333333333333333333 × 0.03 becomes 0.02499999999999999999999999999, which wrongly rounds down to $0.02! Multiplying (per_minute * micros) / 60_000_000 computes 1,500,000 / 60,000,000 = 0.025 with zero loss.
    2. Round once per (dasherId, day): if three orders each earn $0.005 in 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)
    
  6. Deduplicate, group by day, and reconcile dasher totals

    compute_pay ties everything together in three clean phases:

    1. Validate rules up front so bad configuration raises ValueError even on an empty delivery list.
    2. Parse each delivery, skip invalid records or duplicate deliveryIds while recording (index, reason) in errors, and bucket valid deliveries by (dasherId, pickup_date_iso).
    3. Iterate sorted(groups). Because "YYYY-MM-DD" strings sort chronologically, each dasher's days run in exact calendar order, letting paid_until carry across midnight for that dasher and reset to datetime.min when dasher_id changes. When by_day=False, _sum_by_dasher sums 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())
    
  7. 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.86
    
  8. Complete 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:

  1. Order 1 (17:00–17:30, 2.0 mi, $2.00 tip): interval sweep adds 30 active minutes and advances paid_until to 17:30.
  2. Order 2 (17:20–17:50, 1.5 mi, $1.25 bonus): start 17:20 is clipped to paid_until = 17:30, adding 20 new active minutes (50 total) and advancing paid_until to 17:50.
  3. Order 3 (17:35–17:45, 0.5 mi): start 17:35 clips to 17:50 >= 17:45, adding 0 extra minutes while keeping paid_until at 17: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 n records, checking seen_ids for duplicates, and bucketing by (dasherId, date) takes O(n) average time using hash-table lookups; sorting the G group keys takes O(G log G) time; and sorting the k delivery 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 n cleaned delivery dictionaries across groups, up to n seen deliveryIds in seen_ids, up to n error tuples in errors, and G <= n output summary rows.

Edge cases

  • Zero-minute handoffs (pickupTime == dropoffTime): valid; earns base pay, distance, tips, and bonuses with 0 active minutes.
  • Touching, nested, and chained overlaps: back-to-back orders (12:00–12:10 and 12:10–12:20) yield 20 minutes under both policies; a nested order (10:40–10:42 inside 10:15–10:45) contributes 0 extra union minutes without moving paid_until backward.
  • Orders crossing midnight: grouped under the pickup date, while paid_until carries into the same dasher's next date so post-midnight minutes shared with a morning order are paid only once (and paid_until resets to datetime.min when moving to the next dasher).
  • Fractional minutes and half-cent boundaries: durations are tracked in exact integer microseconds, and (per_minute * micros) / 60_000_000 multiplies 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 tip or bonuses (or explicit None) default to 0 and []; strings like "3.2", booleans like True, negative numbers, NaN, UTC offsets, and repeated deliveryIds are skipped and reported in errors.
  • Idempotent rule validation: passing the output of validate_rules (Decimal rates) back into validate_rules or compute_pay works cleanly (idempotency means applying a validation or cleanup step a second time leaves the result unchanged).

Common mistakes

  • Using float and built-in round(..., 2) for currency: float introduces binary representation drift, and Python's round() uses round-half-to-even (round(0.125, 2) == 0.12) instead of ROUND_HALF_UP.
  • Rounding per order instead of per day: three orders with $0.005 distance pay sum to $0.015 -> $0.02 for 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 = end during the interval sweep: if (10:40, 10:42) follows (10:15, 10:45), overwriting paid_until with 10:42 moves the cursor backward and double-pays 10:42–10:45 on the next order.
  • Resetting paid_until at midnight for the same dasher: double-pays minutes after 00:00 when a 23:50–00:20 delivery overlaps a 00:10–00:30 delivery.
  • Forgetting isinstance(True, int) in Python: without an explicit isinstance(value, bool) check, "tip": True silently adds $1.00.
  • Writing raw.get("tip", 0) when JSON contains "tip": null: dict.get returns None when the key exists with value None, causing a TypeError later.

Alternative approaches

  • Per-order active-time splitting (event sweep line): instead of computing only the union duration for the whole day, sort all 2n pickup (+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 (+1 at pickup, -1 at dropoff) that splits each slice's duration equally (slice_duration / concurrent_orders) across active orders, applies max(order_floor, attributed_pay) per order, and sums. To layer peak-hour multipliers (such as 1.5x per-minute rates between 17:00 and 20:00), intersect each active span [start, end] against the sorted peak windows with a two-pointer scan so overlapping peak sub-spans earn per_minute * multiplier and off-peak sub-spans earn per_minute.
  • How could you express the "union" active-time calculation and daily payout aggregation purely in SQL? Store monetary rates and amounts as DECIMAL / NUMERIC rather than FLOAT, and compute each row's preceding watermark paid_until using a SQL window function (an aggregate like MAX(...) 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 by dasher_id carries paid_until across midnight automatically, letting each row contribute GREATEST(dropoff_time - GREATEST(pickup_time, COALESCE(paid_until, pickup_time)), INTERVAL '0 seconds') inside GROUP 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 deliveryId keys 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

Similar questions

More DoorDash interview questions

All 241 DoorDash questions →