Hourly Courier Pay Ledger with Settlement Watermark
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a payroll ledger that records work intervals, tracks accrued cost, and settles wages up to a cutoff time without double-paying.
Courier Pay Ledger
A courier company pays its drivers by the hour. You are given a log of ledger commands and must replay them in order, returning one result per command.
Write a function that takes two parallel lists:
operations: command names.arguments: for each command, the list of its arguments.
The command at index i is operations[i] and its arguments are arguments[i].
Commands
| Command | Arguments | Effect | Result |
|---|---|---|---|
add_driver | [driver_id, hourly_rate] | Register a driver with an hourly rate in US dollars. If the id is already registered, the new rate replaces the old one. | None |
record_delivery | [driver_id, start_time, end_time] | Log a delivery during which the driver worked from start_time to end_time. | None |
get_total_cost | [] | Return the total wages for all recorded deliveries of all drivers, whether or not they have been paid. | a number |
pay_up_to | [pay_time] | Settle all work performed up to and including time pay_time. | None |
get_total_cost_unpaid | [] | Return the total wages that have not yet been settled. | a number |
Cost rules
- Times are integer seconds. The cost of a time span is
span_seconds * hourly_rate / 3600. - The hourly rate used for a driver is the one registered at the moment a cost is queried. A driver's current rate applies to all of their recorded deliveries.
- Every recorded delivery is costed on its own. If a driver's deliveries overlap in time, the overlap is paid once per delivery.
Settlement rules
The ledger keeps a single settlement cutoff, shared by all drivers.
- Before any
pay_up_to, no cutoff exists and nothing is settled. pay_up_to(pay_time)moves the cutoff topay_time, but never backwards. The cutoff becomes the larger of its current value andpay_time. Repeating a payout, or paying up to an earlier time, therefore changes nothing.- For each delivery
[start, end], only the part after the cutoff is unpaid. That is the span frommax(start, cutoff)toend, counted only ifendis greater thanmax(start, cutoff). - This applies to every delivery:
- A delivery in progress at the cutoff (it started before it and ends after it) has its portion up to the cutoff settled and the rest unpaid.
- A delivery recorded after a payout is treated the same way. Whatever part of it lies at or before the current cutoff counts as already settled, and the rest is unpaid.
get_total_cost_unpaidis the sum of the unpaid spans, costed as above.
You may assume that every driver referenced in a delivery is registered by the time a cost query is made, that start_time <= end_time for every delivery, and that every command name is one of the five listed.
Output
Return a list with one entry per command. Entries for add_driver, record_delivery and pay_up_to are None. Entries for the two cost queries are the computed dollar amounts, with no rounding applied.
Constraints
1 <= len(operations) == len(arguments) <= 2000- Times are integers with
0 <= time <= 10^9. - Hourly rates are non-negative numbers.
- Driver ids are strings.
- Cost query results are compared with a small floating-point tolerance.
Examples
Example 1
Input: run_payroll_ledger(['add_driver', 'record_delivery', 'get_total_cost', 'pay_up_to', 'get_total_cost_unpaid'], [['d1', 20], ['d1', 0, 3600], [], [1800], []])
Output: [None, None, 20, None, 10]
Example 2
Input: run_payroll_ledger(['add_driver', 'record_delivery', 'pay_up_to', 'record_delivery', 'get_total_cost_unpaid'], [['d1', 36], ['d1', 0, 1800], [2000], ['d1', 1800, 3600], []])
Output: [None, None, None, None, 16]
Hints
Hint 1
Keep the list of recorded deliveries and a dictionary of current hourly rates. Look rates up only when a cost is queried, so a changed rate applies to all of that driver's deliveries.
Hint 2
Because payouts only ever move forward and apply to every driver, you do not need per-delivery paid flags. A single cutoff value, updated with max, makes repeated and earlier payouts harmless.
Hint 3
For each delivery, the unpaid part starts at max(start, cutoff), or at start if no payout has happened yet. It counts only when end is greater than that point. This handles in-progress and late-recorded deliveries uniformly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Replay the commands in order and keep three pieces of state:
rates: a dictionary from driver id to the current hourly rate.add_driveroverwrites the entry.deliveries: a list of(driver_id, start, end)tuples, appended byrecord_delivery.cutoff: the settlement watermark, initiallyNone.
Payout. pay_up_to(t) sets cutoff = max(cutoff, t), or t if no cutoff exists yet. Payouts therefore cannot pay anything twice. A repeated or earlier payout leaves the cutoff unchanged.
Total cost. Sum (end - start) * rate / 3600 over all deliveries, using each driver's current rate.
Unpaid cost. For each delivery, the settled part is everything at or before the cutoff. The unpaid part therefore starts at max(start, cutoff), or at start if there is no cutoff. If end is later than that point, add (end - unpaid_start) * rate / 3600. Otherwise the delivery is fully settled and adds nothing.
Why it is correct
A single global watermark is enough because a payout settles every driver's work up to a time, and payouts only move the watermark forward. Whether a delivery is complete, in progress, or recorded after the payout, its unpaid portion is exactly the part of [start, end] that lies after the watermark. Clamping the start to the watermark and requiring a positive length handles all three cases uniformly. In the second sample, the delivery from 1800 to 3600 is recorded after the payout to 2000, so only 2000 to 3600 is unpaid: 1600 seconds at $36/hour is $16.
Complexity
add_driver,record_delivery,pay_up_to: O(1) each.- The two cost queries scan all deliveries: O(d), where d is the number of recorded deliveries.
- Space: O(d + number of drivers).
Total time for n commands is O(n * d) in the worst case, which is fine for the stated limits. Running totals could speed up the queries, but the retroactive rate semantics make a plain scan the simplest correct choice.
Reference solution
from typing import List, Optional
def run_payroll_ledger(operations: List[str], arguments: List[List]) -> List[Optional[float]]:
rates = {}
deliveries = []
cutoff = None
results = []
def accrued_cost():
return sum((end - start) * rates[driver_id] / 3600.0
for driver_id, start, end in deliveries)
def unpaid_cost():
total = 0.0
for driver_id, start, end in deliveries:
unpaid_start = start if cutoff is None else max(start, cutoff)
if end > unpaid_start:
total += (end - unpaid_start) * rates[driver_id] / 3600.0
return total
for operation, args in zip(operations, arguments):
if operation == "add_driver":
driver_id, rate = args
rates[driver_id] = rate
results.append(None)
elif operation == "record_delivery":
driver_id, start, end = args
deliveries.append((driver_id, start, end))
results.append(None)
elif operation == "get_total_cost":
results.append(accrued_cost())
elif operation == "pay_up_to":
pay_time, = args
cutoff = pay_time if cutoff is None else max(cutoff, pay_time)
results.append(None)
elif operation == "get_total_cost_unpaid":
results.append(unpaid_cost())
else:
raise ValueError(f"Unknown operation: {operation}")
return results