Courier Earnings from Overlapping Order Events
Greedy & IntervalsAuto-graded · 20 test casesLast updated
Sweep over unsorted start/end events to total concurrency-weighted seconds, validate malformed input, and convert to a half-up rounded dollar string.
Courier Earnings from Overlapping Order Events
A courier works several orders during one day. You are given a log of events, each marking when an order began or finished. Compute the courier's total earnings for the day.
Pay rule
The courier earns $0.30 per minute for every order that is in progress. If k orders are in progress at the same moment, the earning rate at that moment is k times the base rate. Two orders running at once therefore pay double during their overlap.
Pay accrues continuously by the second. One order-second is worth exactly half a cent. Add up the earnings for the whole day first, then round once to whole cents, rounding halves up.
Input
events is a list of dictionaries. Each dictionary describes one event and must have:
"orderId": an identifier for the order. It must not beNoneand must be hashable."type": either the string"START"or the string"END"."timestamp": an integer number of seconds.boolvalues are not accepted.
Events may appear in any order.
Output
Return the total earnings as a string in dollars with exactly two decimal places, such as "0.30" or "12.05". Use no currency symbol and no thousands separators. An empty list yields "0.00".
Validity rules
An order is in progress from its START timestamp up to its END timestamp. Orders that share a timestamp contribute no paid time between those equal moments, and an order whose start and end are equal is valid and earns nothing.
Raise a ValueError (and return no amount) if any of the following holds:
- An event is not a dictionary, or lacks any of the keys
orderId,type,timestamp. orderIdisNoneor unhashable.typeis neither"START"nor"END".timestampis not an integer (including booleans).- An order has two
STARTevents or twoENDevents. - An order is missing its
STARTor itsEND. - An order's
STARTtimestamp is later than itsENDtimestamp.
Constraints
- Use exact integer arithmetic; do not use floating point for money.
- Rounding happens only once, on the final total, and halves round up.
- Timestamps are integers and may be any size that fits in a Python
int. - The number of events can be large, so aim for roughly O(n log n) time.
Examples
Example 1
Input: compute_courier_earnings([{'orderId': 'A', 'type': 'START', 'timestamp': 0}, {'orderId': 'A', 'type': 'END', 'timestamp': 60}])
Output: '0.30'
Example 2
Input: compute_courier_earnings([{'orderId': 'B', 'type': 'END', 'timestamp': 120}, {'orderId': 'A', 'type': 'START', 'timestamp': 0}, {'orderId': 'B', 'type': 'START', 'timestamp': 30}, {'orderId': 'A', 'type': 'END', 'timestamp': 90}])
Output: '0.90'
Example 3
Input: compute_courier_earnings([{'orderId': 'A', 'type': 'START', 'timestamp': 0}, {'orderId': 'A', 'type': 'END', 'timestamp': 1}, {'orderId': 'B', 'type': 'START', 'timestamp': 1}, {'orderId': 'B', 'type': 'END', 'timestamp': 2}])
Output: '0.01'
Hints
Hint 1
Group events by order ID first so you can verify each order has exactly one START and one END, in a sensible order.
Hint 2
Turn each order into two changes on a timeline: +1 concurrent order at its start time and -1 at its end time. Merge changes sharing the same timestamp and sweep the sorted timestamps.
Hint 3
Between consecutive timestamps, add (time gap) * (current active count) to a running total of order-seconds. Each order-second is worth half a cent, so cents = ceil(total / 2), which is (total + 1) // 2 in integers.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Validate and pair events. Walk the list once. Check that each event is a dictionary with the required keys, a non-
NonehashableorderId, atypeofSTARTorEND, and a true integer timestamp. Store each order's start and end in a dictionary keyed by order ID. A second event of the same type for the same order is an error. - Check each order. Every order must have both a start and an end, and the start must not be later than the end. Otherwise raise
ValueError. - Build a timeline. For each order, add +1 at its start time and -1 at its end time in a dictionary keyed by timestamp. This merges changes that share a timestamp and removes any dependence on input order.
- Sweep. Visit the timestamps in sorted order, keeping the current number of active orders. For each gap between consecutive timestamps, add
gap * activeto a running total of order-seconds. Then apply the change at the current timestamp. - Convert to money. At $0.30 per minute, one order-second is worth $0.005, or half a cent. The total in cents is
order_seconds / 2, rounded half up, which is(order_seconds + 1) // 2in integers. Format it as dollars and two-digit cents.
Why it is correct
The active count between two adjacent distinct timestamps is constant, so the earnings in that gap are exactly gap * active * half-cent. Summing over all gaps counts every order-second exactly once. Equal timestamps produce a gap of zero, so they add nothing. Because the arithmetic is integer-only and rounding occurs once at the end, the result is exact and matches the half-up rule. The final check that the active count returns to zero is a safety net, since the per-order validation already guarantees it.
Complexity
- Time: O(n log n), dominated by sorting the distinct timestamps.
- Space: O(n) for the order table and the timeline.
Reference solution
from typing import Dict, List
def compute_courier_earnings(events: List[Dict[str, object]]) -> str:
"""Return the courier's total earnings as a dollar string with two decimals."""
orders = {}
for event in events:
if not isinstance(event, dict) or not all(
key in event for key in ("orderId", "type", "timestamp")
):
raise ValueError("Malformed event")
order_id = event["orderId"]
kind = event["type"]
ts = event["timestamp"]
if order_id is None or kind not in ("START", "END"):
raise ValueError("Malformed event")
if not isinstance(ts, int) or isinstance(ts, bool):
raise ValueError("Timestamp must be an integer number of seconds")
try:
pair = orders.setdefault(order_id, [None, None])
except TypeError:
raise ValueError("orderId must be hashable") from None
slot = 0 if kind == "START" else 1
if pair[slot] is not None:
raise ValueError("Duplicate event type for an order")
pair[slot] = ts
deltas = {}
for start, end in orders.values():
if start is None or end is None or start > end:
raise ValueError("Each order needs a START no later than its END")
deltas[start] = deltas.get(start, 0) + 1
deltas[end] = deltas.get(end, 0) - 1
active = 0
prev = None
order_seconds = 0
for ts in sorted(deltas):
if prev is not None:
order_seconds += (ts - prev) * active
active += deltas[ts]
if active < 0:
raise ValueError("Invalid event sequence")
prev = ts
if active != 0:
raise ValueError("Invalid event sequence")
# $0.30 per minute = half a cent per order-second; round half up once.
cents = (order_seconds + 1) // 2
return f"{cents // 100}.{cents % 100:02d}"